package com.bjpowernode.springboot.autoconfig;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.w3c.dom.DOMImplementation;
public class XmlUtils2 {
public static void main(String[] args) throws Exception {
File inputFile = new File("d:\\test.xml");
File outputFile = new File("d:\\output.xml");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile));
byte[] bu = new byte[1024 * 1024 * 8];
int len;
//将给定的Xpath结合成一个大的字符串
StringBuilder xpaths = new StringBuilder();
while ((len = bis.read(bu)) != -1) {
xpaths.append(new String(bu, 0, len));
}
// 把xml格式的字符串转成Document
Document doc = DocumentHelper.parseText(xpaths.toString());
// 使用xpath语法查询指定元素节点
//List ss2 = doc.selectNodes("/root/bbb/instance/@*");
List ss2 = doc.selectNodes("/root/bbb/instance/@zzz");
// 从查询的节点列表中获取第一位元素(如果你的xpath指定的够精确)
Element s2 = (Element) ss2.get( 0 );
// 把指定的节点值替换成新的值
// Element s3 = s2.addElement("tetet");
//
//
// Element s6 = s3.addElement("44444");
//
// s6.addText("33333");
String newDoc = prettysString(doc);
System.out.println(newDoc);
}
/***
* 格式化xml为string
*
* @param document
* @return
* @throws IOException
*/
protected static String prettysString(Document document) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(document.getXMLEncoding());
StringWriter stringWriter = new StringWriter();
XMLWriter writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.close();
return stringWriter.toString();
}
}
package com.bjpowernode.springboot.autoconfig;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlUtils2 {
static HashMap<String, List<String>> allMap = new HashMap<String, List<String>>();
public static void main(String[] args) {
try {
testGetRoot();
System.out.println(allMap);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件的document对象,然后获取对应的根节点
*
* @author chenleixing
*/
public static void testGetRoot() throws Exception {
SAXReader sax = new SAXReader();// 创建一个SAXReader对象
File xmlFile = new File("d:\\test.xml");// 根据指定的路径创建file对象
Document document = sax.read(xmlFile);// 获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root = document.getRootElement();// 获取根节点
getNodes(root, "");// 从根节点开始遍历所有节点
}
/**
* 对xml格式化并写入文件
*
* @param file
* 文件
* @param documentXML
* 写入的内容
* @throws IOException
*/
protected void writeFile4Pretty(File file, Document document) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(document.getXMLEncoding());
XMLWriter writer = new XMLWriter(new FileWriter(file), format);
writer.write(document);
writer.flush();
writer.close();
}
/***
* 格式化xml为string
*
* @param document
* @return
* @throws IOException
*/
protected static String prettysString(Document document) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(document.getXMLEncoding());
StringWriter stringWriter = new StringWriter();
XMLWriter writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.close();
return stringWriter.toString();
}
/**
* 从指定节点开始,递归遍历所有子节点
*
* @author chenleixing
*/
public static void getNodes(Element node, String pathStr) {
// 当前节点的名称、文本内容和属性
String name = node.getName();
String text = node.getTextTrim();
// System.out.println("当前节点名称:"+name);//当前节点名称
// System.out.println("当前节点的内容:"+text);//当前节点名称
pathStr = pathStr + name + "/";
String pathStrBefore = pathStr;
if (!"".equals(text)) {
List<String> listValue = allMap.get(pathStr + ":");
if (null == listValue) {
listValue = new ArrayList<String>();
}
if (!listValue.contains(text)) {
listValue.add(text);
}
allMap.put(pathStr + ":", listValue);
pathStr = pathStr + ":" + text;
System.out.println(pathStr);
}
List<Attribute> listAttr = node.attributes();// 当前节点的所有属性的list
for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
name = attr.getName();// 属性名称
String value = attr.getValue();// 属性的值
if (!"".equals(name)) {
List<String> listValue = allMap.get(pathStr);
if (null == listValue) {
listValue = new ArrayList<String>();
}
if (!listValue.contains(pathStrBefore + "@" + name)) {
listValue.add(value);
}
allMap.put(pathStrBefore + "@" + name, listValue);
pathStrBefore = pathStrBefore + "@" + name + "[" + value + "]";
System.out.println(pathStrBefore);
}
// System.out.println("属性名称:"+name+"属性值:"+value);
}
// 递归遍历当前节点所有的子节点
List<Element> listElement = node.elements();// 所有一级子节点的list
for (Element e : listElement) {// 遍历所有一级子节点
getNodes(e, pathStr);// 递归
}
}
}
package com.bjpowernode.springboot.autoconfig;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
/**
* @Author Daniel
* @Description 自制工具类:给定Xpath生成XML文件
**/
public class XpathUtils {
static final String NODENAME_SEP = "/";
public static void main(String[] args) throws Exception {
File inputFile = new File("d:\\input.txt");
File outputFile = new File("d:\\output.xml");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile));
byte[] bu = new byte[1024 * 1024 * 8];
int len;
//将给定的Xpath结合成一个大的字符串
StringBuilder xpaths = new StringBuilder();
while ((len = bis.read(bu)) != -1) {
xpaths.append(new String(bu, 0, len));
}
String rootName = xpaths.substring(0, xpaths.indexOf("/"));
String xml = createXML(rootName, xpaths.toString());
bos.write(xml.getBytes());
bos.close();
bis.close();
System.out.println("finished");
}
//创建XML字符串
public static String createXML(String rootName, String xpaths) {
Document doc = createDocument(rootName, null);
Element root = doc.getDocumentElement();
//按行切割字符串
String[] split = xpaths.split("\r\n");
for (String s : split) {
//replaceFirst用来删除root节点的名字
createNode(doc, root, s.replaceFirst(rootName + "/", ""), "somevalue");
}
return getResult(doc);
}
//初始化Document对象
public static Document createDocument(String name, String namespace) {
//前置操作
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
DOMImplementation impl = db.getDOMImplementation();
//必须使用DOMImplementation类中的createDocument方法来创建root节点
Document doc = impl.createDocument(namespace, name, null);
return doc;
}
//创建所有节点
public static void createNode(Document doc, Node parentNode, String childName, String text) {
String[] childNames = childName.split(NODENAME_SEP);
String childNodeName = childNames[0];
//获取到子节点 ccc/:444 childName
Node childNode = getChildByName(parentNode, childNodeName);
// Node childNode = ((Element) parentNode).getElementsByTagName(childNodeName).item(0);//这种写法错误,如果出现同名则会有问题
//不为空说明已经创建过父级节点,然后创建子级节点
if (childNode != null) {
//长度大于1才有子级节点
if (childNames.length > 1) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < childNames.length; i++) {
str.append(childNames[i] + NODENAME_SEP);
}
//递归创建
createNode(doc, childNode, str.toString(), text);
return;
}
}
childNode = doc.createElement(childNodeName);
//由于前面将childNames中的第一个元素作为判断Node是否为空的条件,如果这个节点的上一级不为root的话无法将其添加上去,这段代码就是用来解决这个问题
if (childNames.length > 1) {
//同上面逻辑
StringBuilder str = new StringBuilder();
for (int i = 1; i < childNames.length; i++) {
str.append(childNames[i] + NODENAME_SEP);
}
//与上面不同的是这里要添加节点
parentNode.appendChild(childNode);
createNode(doc, childNode, str.toString(), text);
return;
}
childNode.setTextContent(text);
parentNode.appendChild(childNode);
}
//输出XML
public static String getResult(Document xml) {
Transformer tf = null;
try {
tf = TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
Writer out = new StringWriter();
try {
tf.transform(new DOMSource(xml), new StreamResult(out));
} catch (TransformerException e) {
e.printStackTrace();
}
return out.toString().substring(out.toString().indexOf(">") + 1);
}
public static Node getChildByName(Node parentNode, String childName) {
//获取当前node下的所有子节点
NodeList list = parentNode.getChildNodes();
String nodeName;
//遍历子节点,找出子节点中与形参childName值相同的节点
for (int i = 0; i < list.getLength(); i++) {
nodeName = list.item(i).getNodeName();
if (nodeName.equals(childName))
return list.item(i);
}
//如果没有子节点则返回空值
return null;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<root>
<ccc>444</ccc>
<ccc>555</ccc>
<aaa ddd="999">333</aaa>
<bbb ddd="888">
<ccc>444</ccc>
<instance zzz="333">
<ip>10.1.1.5</ip>
<mask>717</mask>
</instance>
</bbb>
<flw>
<name kkk="">aa</name>
<age>22</age>
<instance_info>
<num attr="bbb">1</num>
<code>0</code>
<instance>
<ip usr="4444">10.1.1.2</ip>
<mask>9999</mask>
</instance>
<instance>
<ip usr="4444">10.1.1.2</ip>
<mask>717</mask>
</instance>
</instance_info>
<instance_info>
<num>2</num>
<code>33</code>
<instance>
<ip usr="333">10.1.1.6</ip>
<mask>9999</mask>
</instance>
<instance>
<ip usr="4444">10.1.1.6</ip>
<mask>878</mask>
</instance>
</instance_info>
</flw>
</root>
package com.bjpowernode.springboot.autoconfig;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class ttt {
static HashMap<String, List<String>> allMap = new HashMap<String, List<String>>();
public static void main(String[] args) {
try {
Document document = DocumentHelper.createDocument();
List<String> list = new ArrayList<>();
list.add("root/ccc/");
list.add("root/ccc/");
list.add("root/aaa/");
list.add("root/aaa/");
list.add("root/bbb/");
list.add("root/bbb/ccc/");
list.add("root/bbb/instance/");
list.add("root/bbb/instance/ip/");
list.add("root/bbb/instance/mask/");
list.add("root/flw/name/");
list.add("root/flw/name/");
list.add("root/flw/age/");
list.add("root/flw/instance_info/num/");
list.add("root/flw/instance_info/num/");
list.add("root/flw/instance_info/code/");
list.add("root/flw/instance_info/instance/ip/");
list.add("root/flw/instance_info/instance/ip/");
list.add("root/flw/instance_info/instance/mask/");
list.add("root/flw/instance_info/instance/ip/");
list.add("root/flw/instance_info/instance/ip/");
list.add("root/flw/instance_info/instance/mask/");
list.add("root/flw/instance_info/num/");
list.add("root/flw/instance_info/code/");
list.add("root/flw/instance_info/instance/ip/");
list.add("root/flw/instance_info/instance/ip/");
list.add("root/flw/instance_info/instance/mask/");
list.add("root/flw/instance_info/instance/ip/");
list.add("root/flw/instance_info/instance/ip/");
list.add("root/flw/instance_info/instance/mask/");
for(String path: list){
Element doc = DocumentHelper.makeElement(document, path);
}
String newDoc = prettysString(document);
System.out.print(newDoc);
} catch (Exception e) {
e.printStackTrace();
}
}
protected static String prettysString(Document document) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(document.getXMLEncoding());
StringWriter stringWriter = new StringWriter();
XMLWriter writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.close();
return stringWriter.toString();
}
}
package com.bjpowernode.springboot.autoconfig;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlUtils {
static HashMap<String, List<String>> allMap = new HashMap<String, List<String>>();
static HashMap<String, List<String>> rootUrlMap = new HashMap<String, List<String>>();
static HashMap<Integer, List<String>> lengthmap = new HashMap<Integer, List<String>>();
static int maxSize = 0;
public static void main(String[] args) {
try {
testGetRoot();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件的document对象,然后获取对应的根节点
*
* @author chenleixing
*/
public static void testGetRoot() throws Exception {
SAXReader sax = new SAXReader();// 创建一个SAXReader对象
File xmlFile = new File("d:\\test.xml");// 根据指定的路径创建file对象
Document document = sax.read(xmlFile);// 获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root = document.getRootElement();// 获取根节点
getNodes(root, "");// 从根节点开始遍历所有节点
// System.out.println("--------------------"+map);
List<String> keyData = new ArrayList<String>();
for (Entry<String, List<String>> entry : rootUrlMap.entrySet()) {
String key = entry.getKey();
int keyLength = key.split("/").length;
if (keyLength > maxSize) {
maxSize = keyLength;
}
List<String> listValue = lengthmap.get(keyLength);
if (null == listValue) {
listValue = new ArrayList<String>();
}
if (!listValue.contains(key)) {
listValue.add(key);
}
lengthmap.put(keyLength, listValue);
// System.out.println(entry.getValue());
keyData.add(key);
}
Document documentNew = DocumentHelper.createDocument();
documentNew.setXMLEncoding("UTF-8");
Element element = documentNew.addElement(lengthmap.get(1).toString().replace("/", ""));
outXml(element, 2);
// String asXML = document.asXML();
//System.out.println(prettysString(documentNew));
// File file = new File("D:/test.xml");
// data2Xml.writeFile4Pretty(file, document);
// Comparator<String> compByLength = (a, b) -> a.split("/").length -
// b.split("/").length;
// keyData.stream().max(compByLength).ifPresent(longest -> {
// System.out.println("\nThe longest name is " + longest);
//
// Document documentNew = DocumentHelper.createDocument();
// documentNew.setXMLEncoding("UTF-8");
// Element element = documentNew.addElement(longest.split("/")[0]);
//
// for(int i=0;i<longest.split("/").length;i++) {
//
//
// element=outXml(element);
// }
//
//
// });
}
/**
* 对xml格式化并写入文件
*
* @param file
* 文件
* @param documentXML
* 写入的内容
* @throws IOException
*/
protected void writeFile4Pretty(File file, Document document) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(document.getXMLEncoding());
XMLWriter writer = new XMLWriter(new FileWriter(file), format);
writer.write(document);
writer.flush();
writer.close();
}
/***
* 格式化xml为string
*
* @param document
* @return
* @throws IOException
*/
protected static String prettysString(Document document) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(document.getXMLEncoding());
StringWriter stringWriter = new StringWriter();
XMLWriter writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.close();
return stringWriter.toString();
}
private static void outXml(Element element, int i) {
if (i > maxSize)
return;
// 路径等于i的集合 root/cc
List<String> rooturllistValue = lengthmap.get(i);
List<Element> nextElementS = new ArrayList<Element>();
for (int j = 0; j < rooturllistValue.size(); j++) {
String rooturlValue = rooturllistValue.get(j);
String[] dataValues = rooturlValue.split("/");
Element nextElement = element.addElement(dataValues[i - 1]);
// {root/bbb/ccc/:=[444], root/bbb/instance/@zzz=[], root/flw/name/@kkk=[],
// root/flw/age/:=[22], root/bbb/instance/mask/:=[717],
// root/flw/instance_info/instance/ip/:=[10.1.1.2, 10.1.1.5, 10.1.1.9],
// root/ccc/:=[444, 555], root/flw/instance_info/instance/mask/:=[9999, 717,
// 878], root/flw/instance_info/num/@attr=[bbb], root/aaa/:=[333],
// root/flw/instance_info/code/:=[0, 33], root/aaa/@ddd=[999],
// root/bbb/@ddd=[888], root/flw/instance_info/num/:=[1, 2],
// root/flw/name/:=[aa], root/bbb/instance/ip/:=[10.1.1.5]}
List<String> textList = allMap.get(rooturlValue + ":");
if (null != textList) {
for (String text : textList) {
if (null != text) {
nextElement.setText("1");
}
List<String> attrList = allMap.get(rooturlValue + "@" + text);
for (String attr : textList) {
if (null != text) {
nextElement.addAttribute("FormatVersion", "01");
nextElement.add(nextElement);
}
}
nextElementS.add(nextElement);
}
}
}
for (int k = 0; k < nextElementS.size(); k++) {
Element nextElement = nextElementS.get(k);
i = i + 1;
outXml(nextElement, i);
}
}
/**
* 从指定节点开始,递归遍历所有子节点
*
* @author chenleixing
*/
public static void getNodes(Element node, String pathStr) {
// 当前节点的名称、文本内容和属性
String name = node.getName();
String text = node.getTextTrim();
// System.out.println("当前节点名称:"+name);//当前节点名称
// System.out.println("当前节点的内容:"+text);//当前节点名称
pathStr = pathStr + name + "/";
List<String> rootUrllistValue = rootUrlMap.get(pathStr);
if (null == rootUrllistValue) {
rootUrllistValue = new ArrayList<String>();
}
if (!rootUrllistValue.contains(pathStr)) {
rootUrllistValue.add(pathStr);
}
rootUrlMap.put(pathStr, rootUrllistValue);
String pathStrBefore = pathStr;
if (!"".equals(text)) {
List<String> listValue = allMap.get(pathStr + ":");
if (null == listValue) {
listValue = new ArrayList<String>();
}
if (!listValue.contains(text)) {
listValue.add(text);
}
allMap.put(pathStr + ":", listValue);
pathStr = pathStr + ":" + text;
System.out.println(pathStr);
}
List<Attribute> listAttr = node.attributes();// 当前节点的所有属性的list
for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
name = attr.getName();// 属性名称
String value = attr.getValue();// 属性的值
if (!"".equals(name)) {
List<String> listValue = allMap.get(pathStr);
if (null == listValue) {
listValue = new ArrayList<String>();
}
if (!listValue.contains(pathStrBefore + "@" + name)) {
listValue.add(value);
}
allMap.put(pathStrBefore + "@" + name, listValue);
pathStrBefore = pathStrBefore + "@" + name + "[" + value + "]";
System.out.println(pathStrBefore);
}
// System.out.println("属性名称:"+name+"属性值:"+value);
}
// 递归遍历当前节点所有的子节点
List<Element> listElement = node.elements();// 所有一级子节点的list
for (Element e : listElement) {// 遍历所有一级子节点
getNodes(e, pathStr);// 递归
}
}
}