Dom4J的基本使用

初始化数据

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <RESULT>
 3     <VALUE>  
 4         <NO>A1234</NO>  
 5         <ADDR>陕西省西安市</ADDR>
 6     </VALUE>
 7     <VALUE>  
 8         <NO>D1234</NO>  
 9         <ADDR>陕西省咸阳市</ADDR>
10     </VALUE>
11 </RESULT>

DOM解析

 1 package com.example.dom4j;
 2 
 3 import org.w3c.dom.Document;
 4 import org.w3c.dom.NodeList;
 5 
 6 import javax.xml.parsers.DocumentBuilder;
 7 import javax.xml.parsers.DocumentBuilderFactory;
 8 import java.io.File;
 9 
10 /**
11  * @program: dom4j
12  * @description:
13  * @author: 
14  * @create: 2019-03-23 13:51:22
15  */
16 public class Dom {
17     public static void main(String[] args) {
18         File file = new File("D://data.xml");
19         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
20         try {
21             DocumentBuilder builder = factory.newDocumentBuilder();
22             Document doc = builder.parse(file);
23             NodeList n1 = doc.getElementsByTagName("VALUE");
24             for (int i = 0; i < n1.getLength(); i++) {
25                 System.out.println("车牌号 = " + doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());
26                 System.out.println("地址 = " + doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());
27             }
28 
29         } catch (Exception e) {
30             e.printStackTrace();
31         }
32     }
33 }

DOM4J解析

 1 package com.example.dom4j;
 2 
 3 import org.dom4j.Document;
 4 import org.dom4j.DocumentException;
 5 import org.dom4j.Element;
 6 import org.dom4j.io.SAXReader;
 7 
 8 import java.io.File;
 9 import java.util.Iterator;
10 
11 /**
12  * @program: dom4j
13  * @description:
14  * @author: 
15  * @create: 2019-03-23 14:07:56
16  */
17 public class Dom4j {
18     public static void main(String[] args) {
19         long lasting = System.currentTimeMillis();
20         File file = new File("D://data.xml");
21         SAXReader saxReader = new SAXReader();
22         try {
23             Document doc = saxReader.read(file);
24             Element rootElement = doc.getRootElement();
25             System.out.println("rootElement = " + rootElement);
26             Iterator value = rootElement.elementIterator("VALUE");
27             while (value.hasNext()){
28                 Element element  = (Element) value.next();
29                 System.out.println("车牌号码:"+element.elementText("NO"));
30                 System.out.println("车主地址:"+element.elementText("ADDR"));
31             }
32 
33         } catch (DocumentException e) {
34             e.printStackTrace();
35         }
36 
37     }
38 }

猜你喜欢

转载自www.cnblogs.com/gaohuanhuan/p/10583831.html