一、数据准备
1、文件头实体类
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、人员信息实体类
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对象
/*** 创建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)添加子节点
/*** 添加子节点* @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字符串
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)测试
@Testpublic 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字符串
@Testpublic 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、添加依赖
<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)示例代码
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)测试方法
@Testpublic 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
@Testpublic 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 - 张三