Dom4j的一个小例子,用于解析xml文件的元素获取方式

 1 import java.io.File;
 2 import java.io.IOException;
 3 
 4 import javax.xml.parsers.ParserConfigurationException;
 5 
 6 import org.dom4j.Document;
 7 import org.dom4j.DocumentException;
 8 import org.dom4j.Element;
 9 import org.dom4j.io.SAXReader;
10 import org.xml.sax.SAXException;
11 
12 public class Dom4jDemo {
13     public static void main(String[] args) throws ParserConfigurationException, DocumentException, SAXException, IOException {
14         SAXReader saxReader = new SAXReader();// new读取的类
15         Document doc = saxReader.read(new File("F:\\MyEclipse Work\\lj_API\\XML\\com\\luo\\kcit\\XML\\Dom4j\\student.xml"));
16         // 读取指定的文档
17         Element root = doc.getRootElement();// 返回元素节点
18 
19         System.out.println("root element: " + root.getName());// 输出根节点名称
20         
21         Element e = root.element("student");
22 
23         Element userId = e.element("userId");//判断是否有userid这个元素,有的话,返回到Element类型的userId
24         System.out.print(userId.getName()+":"+userId.getData()+"  ");
25         System.out.println("id:" + userId.attributeValue("id"));// 返回元素的字段
26         
27         Element name = e.element("name");
28         System.out.println(name.getName() + ": " + name.getData());
29 
30         Element sex  = e.element("sex");
31         System.out.println(sex.getName()+":"+sex.getData());    
32 
33     }
34 }
<?xml version="1.0" encoding="UTF-8"?>
<cla>
    <student>
        <userId id="1">A110</userId>
        <name>Toolo</name>
        <age>23</age>
        <sex></sex>
    </student>
</cla>


结果:

//得到元素,以及值

posted @ 2013-12-30 11:27  ζ  简单ヾ°  阅读(2311)  评论(0编辑  收藏  举报