欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

Dom4J的基本使用

发布时间:2025/7/25 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 }

 

转载于:https://www.cnblogs.com/gaohuanhuan/p/10583831.html

总结

以上是生活随笔为你收集整理的Dom4J的基本使用的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。