Dom4J的基本使用
生活随笔
收集整理的這篇文章主要介紹了
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的基本使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 模式识别第一课
- 下一篇: 题解 P2387 【[NOI2014]魔