1 package com.java1234.action; 2 3 import java.io.File; 4 import java.util.List; 5 6 import org.dom4j.Document; 7 import org.dom4j.DocumentException; 8 import org.dom4j.Element; 9 import org.dom4j.io.SAXReader; 10 11 /* 12 * Dom4j测试类 13 */ 14 public class Dom4jTest2 { 15 public static void main(String[] args) throws DocumentException { 16 Element e = null; 17 // new一个文件 18 File file = new File("C:/Users/Wei/workspace/HeadFirstStruts2Chap08/src/com/java1234/action/ccc.xml"); 19 System.out.println(file); 20 SAXReader reader = new SAXReader(); 21 // 用SAXReader来读取文件,并转换成Document, 22 Document doc = reader.read(file); 23 // 使用Document的selectNodes来读取节点,返回list 24 List<Object> list2 = doc.selectNodes("/syptRequest/syptGsdjxx/NSRMC"); 25 if (list2.size() > 0) { 26 e = (Element) list2.get(0); 27 } 28 System.out.println("list2.size():"+list2.size()); 29 if (null != e) { 30 Object obj = e.getData(); 31 System.out.println("----------" + obj); 32 } else { 33 System.out.println("Element为空"); 34 } 35 36 } 37 }
ccc.xml:
1 <syptRequest> 2 <syptGsdjxx> 3 <SCJYDZ>重庆市渝北区锦坪街</SCJYDZ> 4 <NSRSBH>432894129412044X</NSRSBH> 5 <NSRMC>重庆市交通设施有限公司</NSRMC> 6 <SQXH>qw4r213412</SQXH> 7 <HY_MC>其他电子产品零售</HY_MC> 8 <ZZJG_DM>asf14234</ZZJG_DM> 9 <SHXYDM/> 10 <HY_DM>5279</HY_DM> 11 <SCJYDLXDH/> 12 <HYMX>其他电子产品零售</HYMX> 13 <ND>2008</ND> 14 </syptGsdjxx> 15 </syptRequest>
执行结果:
C:\Users\Wei\workspace\HeadFirstStruts2Chap08\src\com\java1234\action\ccc.xml
list2.size():1
----------重庆市交通设施有限公司