一、数据准备
1、文件头实体类
java
package com.xiaobai.xmlpractice;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @Author 王天文
* @Date 2024/12/18 21:46
* @Description: xml头
*/
@AllArgsConstructor
@Data
public class Head {
private String desc;
private String name;
private String id;
}
2、人员信息实体类
java
package com.xiaobai.xmlpractice;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @Author 王天文
* @Date 2024/12/18 20:41
* @Description:
*/
@AllArgsConstructor
@Data
public class Person {
private Integer id;
private String name;
private Integer age;
private String sex;
private String account;
private String profession;
}
二、使用org.w3c.dom操作xml
1、创建xml
(1)创建document对象
java
/**
* 创建document对象
* @return
* @throws Exception
*/
public Document createDoc() throws Exception {
// 创建一个新的Document对象
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
return doc;
}
(2)添加子节点
java
/**
* 添加子节点
* @param doc document对象
* @param parentElement 上级节点
* @param tagName 标签名称
* @param value 标签值
*/
public void addElement(Document doc, Element parentElement, String tagName, String value) {
Element element = doc.createElement(tagName);
element.appendChild(doc.createTextNode(value));
parentElement.appendChild(element);
}
(3)根据数据生成xml字符串
java
public String createXmlStr() throws Exception {
// 创建一个新的Document对象
Document doc = createDoc();
// 根结点
Element root = doc.createElement("root");
doc.appendChild(root);
// 数据头
Element headElement = doc.createElement("head");
headElement.appendChild(doc.createTextNode("人员信息"));
root.appendChild(headElement);
// 数据结点
Element bodyElement = doc.createElement("body");
root.appendChild(bodyElement);
addData(doc, bodyElement);
// 设置Transformer并指定XML声明头部
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
// 生成XML字符串
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult stringResult = new StreamResult(writer);
transformer.transform(source, stringResult);
// xml字符串
String xmlContent = writer.toString();
return xmlContent;
}
// 添加数据
public void addData(Document doc, Element parentElement) {
Person person = new Person(1, "张三", 29, "男", "zhangsan", "程序员");
addElement(doc, parentElement, "id", String.valueOf(person.getId()));
addElement(doc, parentElement, "name", person.getName());
addElement(doc, parentElement, "age", String.valueOf(person.getAge()));
addElement(doc, parentElement, "account", person.getAccount());
addElement(doc, parentElement, "profession", person.getProfession());
}
(4)测试
java
@Test
public void testCreate() throws Exception {
String xmlStr = createXmlStr();
log.info(xmlStr);
}
输出:
16:39:24.426 [main] INFO com.xiaobai.xmlpractice.W3CDocTest - <?xml version="1.0" encoding="ISO-8859-1"?><root><head>人员信息</head><body><id>1</id><name>张三</name><age>29</age><account>zhangsan</account><profession>程序员</profession></body></root>
2、解析xml字符串
java
@Test
public void testParseXml() throws Exception {
String xmlContent = createXmlStr();
// 解析xml字符串
DocumentBuilderFactory analyzeBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder analyzeBuilder = analyzeBuilderFactory.newDocumentBuilder();
// 字符串转换成document对象
Document document = analyzeBuilder.parse(new InputSource(new StringReader(xmlContent)));
NodeList idNodeList = document.getElementsByTagName("name");
String nodeValue = idNodeList.item(0).getChildNodes().item(0).getNodeValue();
log.info(nodeValue);
}
输出:
16:41:06.619 [main] INFO com.xiaobai.xmlpractice.W3CDocTest - 张三
三、使用dom4j操作xml
1、添加依赖
XML
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
</dependency>
2、创建xml
(1)示例代码
java
public String createXmlStr() {
Document document = DocumentHelper.createDocument();
// 根节点
Element rootElement = document.addElement("root");
/*添加数据头*/
// head节点
Element headElement = rootElement.addElement("head");
Head head = new Head("请求报文头", "技术有限公司", "1");
// 添加desc子节点
headElement.addElement("desc").addText(head.getDesc());
// 添加name子节点
headElement.addElement("name").addText(head.getName());
// 添加id子节点
headElement.addElement("id").addText(head.getId());
// 创建data节点
Element bodyElement = rootElement.addElement("data");
// 添加数据信息
Element infoElement = bodyElement.addElement("info");
infoElement.addElement("id").addText("00001");
infoElement.addElement("name").addText("张三");
infoElement.addElement("age").addText("29");
// 设置xml编码
document.setXMLEncoding("ISO-8859-1");
return document.asXML();
}
(2)测试方法
java
@Test
public void createTest() {
String xmlStr = createXmlStr();
log.info(xmlStr);
}
输出:
16:42:53.724 [main] INFO com.xiaobai.xmlpractice.Dom4jTest - <?xml version="1.0" encoding="ISO-8859-1"?>
<root><head><desc>请求报文头</desc><name>技术有限公司</name><id>1</id></head><data><info><id>00001</id><name>张三</name><age>29</age></info></data></root>
3、解析xml
java
@Test
public void parseTest() throws Exception {
String xmlStr = createXmlStr();
Document document = DocumentHelper.parseText(xmlStr);
// 获取根节点
Element rootElement = document.getRootElement();
// 获取data节点
List<Element> dataElements = rootElement.elements("data");
Element dataElement = dataElements.get(0);
// 获取info节点
List<Element> infoElements = dataElement.elements("info");
Element infoElement = infoElements.get(0);
// 获取name节点
Element nameElement = infoElement.element("name");
log.info(nameElement.getText());
}
输出:
16:45:19.682 [main] INFO com.xiaobai.xmlpractice.Dom4jTest - 张三