• pom.xml增加Dom4j的相关依赖
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>
  • 操作Xml
// 解析xml

// xml文本
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<Interface><Entry DoFlag=\"I\"><Guid>e12de5f4-e067-4f07-84e5-0b8015b7aeb9</Guid></Entry></Interface>";
// 解析字符串
Document doc = DocumentHelper.parseText(xmlStr);
// 先获取根节点
Element rootElement = doc.getRootElement();
// 获取xml中某个节点
Element anInterface = rootElement.element("Entry");
// 获取节点属性
String doFlag = anInterface.attributeValue("DoFlag");
System.out.println(doFlag);
Element guid = anInterface.element("Guid");
// 获取节点文本
String text = guid.getText();
System.out.println(text);

// 组装xml

// 创建一个Document对象
Document doc = DocumentHelper.createDocument();
// 增加节点
Element interfaceElement = doc.addElement("Interface");
Element entry = interfaceElement.addElement("Entry");
// 设置节点属性
entry.addAttribute("DoFlag", "I");
Element guid = entry.addElement("Guid");
// 设置节点文本
guid.setText(RandomUtil.randomUUID());
// 打印组装的xml
System.out.println(doc.asXML());

# To Be Continued!😎

Last Updated: 6/30/2021, 9:26:27 AM