`
wangzheguilai
  • 浏览: 21196 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
收藏列表
标题 标签 来源
JDOM、DOM4j读取XML文件(SAXReader) jdom、dom4j读取xml文件(saxreader) http://uule.iteye.com/blog/821781
2010-11-24

JDOM、DOM4j读取XML文件(SAXReader)
博客分类: XML
 
XML.netBlogStruts农业.




Java代码  
1.<students>    
2.    <student age="25"><!--如果没有age属性,默认的为20-->    
3.        <name>崔卫兵</name>    
4.        <college>PC学院</college>    
5.        <telephone>62354666</telephone>    
6.        <notes>男,1982年生,硕士,现就读于北京邮电大学</notes>   
7.    </student>    
8.    <student age="26">    
9.        <name>cwb</name>    
10.        <college leader="学院领导">PC学院</college><!--如果没有leader属性,默认的为leader-->   
11.        <telephone>62358888</telephone>    
12.        <notes>男,1987年生,硕士,现就读于中国农业大学</notes>    
13.    </student>   
14.</students>   
 
JDOM读取: 



Java代码  
1.SAXBuilder builder = new SAXBuilder();    
2.       org.jdom.Document doc = builder.build(new File("F:/xmltest.xml"));    
3.       Element foo = doc.getRootElement();    
4.       List allChildren = foo.getChildren();    
5.       for (int i = 0; i < allChildren.size(); i++) {    
6.           System.out.println( ((Element) allChildren.get(i)).getChild("name").getText());    
7.           System.out.println("((Element) allChildren.get(i)).getChild("space").getText());     
 
 DOM4J读取XML: 

 
 


Java代码  
1.public void testRead() throws DocumentException, FileNotFoundException{  
2.        SAXReader reader=new SAXReader();  
3.  
4.        Document doc=reader.read("D:/myeclipseWorkspace/Struts/src/test.xml");  
5.        Element root =doc.getRootElement();  
6.        for(Iterator it=root.elementIterator();it.hasNext();){  
7.            Element element=(Element)it.next();  
8.  
9.            System.out.println(element.attribute("age").getName()+" == "+element.attribute("age").getValue());  
10.            System.out.println(element.attributeValue("age"));  
11.            System.out.println(element.getName());  
12.            for(Iterator itt=element.elementIterator();itt.hasNext();){  
13.                //System.out.println(element.attributeValue("age"));  
14.                Element el=(Element)itt.next();  
15.                System.out.println(el.getName()+"=="+el.getText());    
16.                //getText()获取的是两个标签间的数据如"<name>崔卫兵</name>"中的崔卫兵  
17.                //getName()获取的是标签名,即“<student age="25"><name>崔卫兵</name>”中的age和name  
18.                //attributeValue("age")可获取age的值即25  
19.            }  
20.            System.out.println("==================");             
21.        }  
22.    }  
 
  结果:
 
 
 


Java代码  
1.age == 25  
2.25  
3.student  
4.name==崔卫兵  
5.college==PC学院  
6.telephone==62354666  
7.notes==男,1982年生,硕士,现就读于北京邮电大学  
8.==================  
9.age == 26  
10.26  
11.student  
12.name==cwb  
13.college==PC学院  
14.telephone==62358888  
15.notes==男,1987年生,硕士,现就读于中国农业大学  
16.==================  
17.age == 45  
18.45  
19.student  
20.name==xxxxx  
21.college==xxx学院  
22.telephone==66666666  
23.notes==注视中,注释中  
24.==================  
25.age == 12  
26.12  
27.student  
28.name==lxx  
29.college==yyyy学院  
30.telephone==88888888  
31.notes==注视中111,注释中222  
32.==================  
 
DOM读取XML: 

XML文件:
 


Java代码  
1.<?xml version="1.0" encoding="gb2312"?>  
2.<books>  
3.<book attr="T001" id="idd1">  
4.     <name>第一本书</name>  
5.     <price>$14.09</price>  
6.</book>  
7.<book attr="T002" id="idd2">  
8.     <name>第二本书</name>  
9.     <price>$19.89</price>  
10.</book>  
11.<book attr="T003" id="idd3">  
12.     <name>第三本书</name>  
13.     <price>$26.00</price>  
14.</book>  
15.</books>  
 
 读取:
 


Java代码  
1.public void parserXml2(String fileName) {  
2.        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();  
3.        try {  
4.            DocumentBuilder dombuilder = domfac.newDocumentBuilder();  
5.            // 方法1  
6.            Document doc = dombuilder.parse(fileName);  
7.            /* 
8.             * 方法2 InputStream is = new FileInputStream("F:\\ABC.xml"); Document 
9.             * doc = dombuilder.parse(is); 
10.             */  
11.  
12.            /* 
13.             * 方法三如果要解析字符串result= 
14.             * "<?xml version=\"1.0\" encoding=\"gb2312\"?><books><book attribute=\"T001\"><name>第一本书</name><price>$14.09& lt;/price></book><book attribute=\"T002\"><name>第二本书</name><price>$19.89& lt;/price></book><book attribute=\"T003\"><name>第三本书</name><price>$26.00& lt;/price></book></books>" 
15.             * ;就用此方法 StringReader rd = new StringReader(result); InputSource is 
16.             * = new InputSource(rd); Document doc=dombuilder.parse(is); 
17.             */  
18.            Element root = doc.getDocumentElement();  
19.            NodeList books = root.getChildNodes();  
20.            if (books != null) {  
21.                for (int i = 0; i < books.getLength(); i++) {  
22.                    Node book = books.item(i);  
23.                    if (book.getNodeType() == Node.ELEMENT_NODE) {  
24.                        String attr = book.getAttributes().getNamedItem("attr").getNodeValue();  
25.                        String id = book.getAttributes().getNamedItem("id").getNodeValue();  
26.                        System.out.print(attr+" "+ id);  
27.  
28.                        for (Node node = book.getFirstChild(); node != null; node = node  
29.                                .getNextSibling()) {  
30.                            if (node.getNodeType() == Node.ELEMENT_NODE) {  
31.                                if (node.getNodeName().equals("name")) {  
32.                                    String name = node.getNodeValue();  
33.                                    String name1 = node.getFirstChild().getNodeValue();  
34.                                    System.out.print(" " + name);  
35.                                    System.out.print(" " + name1);  
36.                                }  
37.                                if (node.getNodeName().equals("price")) {  
38.                                    String price = node.getFirstChild().getNodeValue();  
39.                                    System.out.println(" " + price);  
40.                                }  
41.                            }  
42.                        }  
43.                    }  
44.                }  
45.            }  
46.        } catch (ParserConfigurationException e) {  
47.        } catch (FileNotFoundException e) {  
48.        } catch (SAXException e) {  
49.        } catch (IOException e) {  
50.        }  
51.    }  
 
该实例参考:http://www.360doc.com/content/07/1213/14/13829_891246.shtml 

 
 
二、创建XML 

DOM4J创建XML: 



Java代码  
1./** 
2.     * 创建XML 
3.     * @throws Exception 
4.     */  
5.    public void testWrite() throws Exception{  
6.  
7.        Document document = DocumentHelper.createDocument();  
8.        Element root = document.addElement("root");  //根节点  
9.        for(int i=0;i<10;i++){  
10.        Element element1 = root.addElement("user")  
11.                                .addAttribute("name","Alex"+i)  
12.                                .addAttribute("id", "id"+i)  
13.                                .addText("我是信息");  
14.          
15.        }  
16.        XMLWriter writer = new XMLWriter(new FileOutputStream("D:/myeclipseWorkspace/Struts/src/output.xml"));  
17.        writer.write(document);  
18.        writer.close();  
19.    }  
 
 输出方法2:
 


Java代码  
1.XMLOutputter XMLOut = new XMLOutputter();  
2.File filePath = new File("D:/temp");  
3.if (!filePath.exists()) {  
4.   filePath.mkdirs();  
5.}  
6.System.out.println("filePath==========="+filePath);           
7.XMLOut.output(doc, new FileOutputStream(filePath + "/areaPie.xml"));  
   
结果:
 
 
 


Java代码  
1.<?xml version="1.0" encoding="UTF-8"?>  
2.  
3.<root>  
4.  
5.<user name="Alex0" id="id0">我是信息</user>  
6.  
7.<user name="Alex1" id="id1">我是信息</user>  
8.  
9.<user name="Alex2" id="id2">我是信息</user>  
10.  
11.<user name="Alex3" id="id3">我是信息</user>  
12.  
13.<user name="Alex4" id="id4">我是信息</user>  
14.  
15.<user name="Alex5" id="id5">我是信息</user>  
16.  
17.<user name="Alex6" id="id6">我是信息</user>  
18.  
19.<user name="Alex7" id="id7">我是信息</user>  
20.  
21.<user name="Alex8" id="id8">我是信息</user>  
22.  
23.<user name="Alex9" id="id9">我是信息</user>  
24.  
25.</root>  
 
 
 
JDOM创建XML: 



Java代码  
1.import java.io.FileOutputStream;     
2. import java.io.IOException;     
3. import org.jdom.Document;     
4. import org.jdom.Element;     
5. import org.jdom.JDOMException;     
6. import org.jdom.output.XMLOutputter;     
7.       
8. public class Java2XML {     
9.       
10.     public void BuildXMLDoc() throws IOException, JDOMException {     
11.       
12.        // 创建根节点 list;     
13.         Element root = new Element("list");     
14.             
15.        // 根节点添加到文档中;     
16.         Document Doc = new Document(root);     
17.       
18.        // 此处 for 循环可替换成 遍历 数据库表的结果集操作;     
19.        for (int i = 0; i < 5; i++) {     
20.                 
21.            // 创建节点 user;     
22.            Element elements = new Element("user");     
23.                 
24.            // 给 user 节点添加属性 id;     
25.            elements.setAttribute("id", "" + i);     
26.                 
27.            // 给 user 节点添加子节点并赋值;     
28.            // new Element("name")中的 "name" 替换成表中相应字段,setText("xuehui")中 "xuehui 替换成表中记录值;     
29.            elements.addContent(new Element("name").setText("xuehui"));    
30.            elements.addContent(new Element("age").setText("28"));    
31.            elements.addContent(new Element("sex").setText("Male"));    
32.      
33.            // 给父节点list添加user子节点;    
34.            root.addContent(elements);    
35.      
36.        }    
37.         XMLOutputter XMLOut = new XMLOutputter();    
38.            
39.        // 输出 user.xml 文件;    
40.         XMLOut.output(Doc, new FileOutputStream("user.xml"));    
41.     }    
42.      
43.     public static void main(String[] args) {    
44.        try {    
45.            Java2XML j2x = new Java2XML();    
46.            System.out.println("生成 mxl 文件...");    
47.            j2x.BuildXMLDoc();    
48.        } catch (Exception e) {    
49.            e.printStackTrace();    
50.        }    
51.     }    
52.      
53. }        
54.      
55. 生成的 user.xml  文件    
56.      
57. <?xml version="1.0" encoding="UTF-8"?>    
58. <list>    
59.     <user id="0">    
60.         <name>xuehui</name>    
61.         <age>28</age>    
62.         <sex>Male</sex>    
63.     </user>    
64.     <user id="1">    
65.         <name>xuehui</name>    
66.         <age>28</age>    
67.         <sex>Male</sex>    
68.     </user>    
69.     <user id="2">    
70.         <name>xuehui</name>    
71.         <age>28</age>    
72.         <sex>Male</sex>    
73.     </user>    
74.     <user id="3">    
75.         <name>xuehui</name>    
76.         <age>28</age>    
77.         <sex>Male</sex>    
78.     </user>    
79.     <user id="4">     
80.         <name>xuehui</name>     
81.         <age>28</age>     
82.         <sex>Male</sex>     
83.     </user>     
84. </list>     
 
 该例子来源:http://zc4530.iteye.com/blog/70062
 
具体XML操作参见:
 
http://blog.csdn.net/wlh269/archive/2008/08/31/2855461.aspx
 
DOM4J  学习笔记:
 
http://heavyz.sourceforge.net/homepage/homepage_zh/comp/notes/dom4j.html
 
 
 
DOM创建XML方式: 



Java代码  
1.package com.techson.himsnanhwa.admin.web;  
2.import java.io.FileNotFoundException;  
3.import java.io.FileOutputStream;  
4.import java.io.IOException;  
5.import java.io.PrintWriter;  
6.import javax.xml.parsers.DocumentBuilder;  
7.import javax.xml.parsers.DocumentBuilderFactory;  
8.import javax.xml.parsers.ParserConfigurationException;  
9.import javax.xml.transform.OutputKeys;  
10.import javax.xml.transform.Transformer;  
11.import javax.xml.transform.TransformerConfigurationException;  
12.import javax.xml.transform.TransformerException;  
13.import javax.xml.transform.TransformerFactory;  
14.import javax.xml.transform.dom.DOMSource;  
15.import javax.xml.transform.stream.StreamResult;  
16.import org.w3c.dom.Document;  
17.import org.w3c.dom.Element;  
18.import org.w3c.dom.Node;  
19.import org.w3c.dom.NodeList;  
20.import org.xml.sax.SAXException;  
21.  
22.public class DomDemo{  
23.    private Document doc;  
24.  
25.    DomDemo() {  
26.        try {  
27.            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
28.            DocumentBuilder builder = factory.newDocumentBuilder();  
29.            doc = builder.newDocument();  
30.        } catch (ParserConfigurationException e) {  
31.            System.out.println(e.getMessage());  
32.        }  
33.    }     
34.    /** 
35.     * 都是用  doc.createElement("");创建 
36.     * 层次结构使用appendChild(name); 实现 
37.     */  
38.    public void createXml(String fileName) {  
39.        Element root = doc.createElement("employees");  
40.        doc.appendChild(root);  
41.          
42.        Element employee = doc.createElement("employee");  
43.          
44.        Element name = doc.createElement("name");  
45.        name.appendChild(doc.createTextNode("小明"));  
46.        name.setAttribute("id", "2006414");   //设置id  
47.        employee.appendChild(name);  
48.          
49.        Element sex = doc.createElement("sex");  
50.        sex.appendChild(doc.createTextNode("m"));  
51.        employee.appendChild(sex);  
52.          
53.        Element age = doc.createElement("age");  
54.        age.appendChild(doc.createTextNode("30"));  
55.        employee.appendChild(age);  
56.          
57.        root.appendChild(employee);  
58.          
59.        TransformerFactory tf = TransformerFactory.newInstance();  
60.        try {  
61.            Transformer transformer = tf.newTransformer();  
62.            DOMSource source = new DOMSource(doc);  
63.            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");  
64.            transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
65.              
66.            PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));  
67.            StreamResult result = new StreamResult(pw);  
68.            transformer.transform(source, result);  
69.            System.out.println("生成XML文件成功!");  
70.        } catch (TransformerConfigurationException e) {  
71.        } catch (IllegalArgumentException e) {  
72.        } catch (FileNotFoundException e) {  
73.        } catch (TransformerException e) {  
74.        }  
75.    }  
76.      
77.    public static void main(String[] args){  
78.        String fileName = "D:\\dom2.xml";  
79.        DomDemo domDemo = new DomDemo();  
80.        domDemo.createXml(fileName);  
81.  
82.    }  
83.}  
 
 结果:
 


Java代码  
1.<?xml version="1.0" encoding="utf-8"?>  
2.<employees>  
3.    <employee>  
4.        <name id="2006414">小明</name>  
5.        <sex>m</sex>  
6.        <age>30</age>  
7.    </employee>  
8.</employees>  
   
 
 
总结: 



Document document=new SAXReader.reader(“xml文路径/文件名xxx.xml”);//得到Document对象

 Element root = document.getRootElement()//获得根节点

 Iterator it=root.elementIterator(); //从根节点遍历子节点

 Iterator iterator=element.elementIterator(); //再从子节点在遍历其子节点

 对节点访问其属性用:Attribute leaderAttr =Element. attribute(“xxx”);

 对节点访问其某个属性leaderAttr的名称:leaderAttr.getName();
 对节点访问其某个属性leaderAttr的值:leaderAttr.getValue()

 对节点访问其名称:Element.getName();

 对节点访问其文本:Element. getText(); 

创建XML:   
Document document = DocumentHelper.createDocument(); 
Element root = document.addElement("root"); //根节点 


或
 


Element root = new Element("pie");
 Document doc = new Document(root);
   

详解Java解析XML的四种方法:
 
    http://developer.51cto.com/art/200903/117512.htm 

java中四种操作(DOM、SAX、JDOM、DOM4J)xml方式详解与比较:
 
   http://hi.baidu.com/drager_000/blog/item/9ba51937a85c533f0b55a961.html 

 
 
各种属性:
 
http://yifeng.iteye.com/blog/207239
Global site tag (gtag.js) - Google Analytics