Java dom4j解析XML

转载:http://www.blogjava.net/Todd/archive/2010/05/22/321618.html

jar下载地址:http://sourceforge.net/projects/dom4j/files/?source=navbar

一.Document 对象相关   

      1. 读取XML文件,获得document对象.   
            SAXReader reader = new SAXReader();   
            Document   document = reader.read(new File("input.xml"));   

       2.解析XML形式的文本,得 到document对象.   
            String text = "<members></members>";   
            Document document = DocumentHelper.parseText(text);   

      3.主动创建document 对象.   
            Document document = DocumentHelper.createDocument();   
            Element root = document.addElement("members");// 创建根节点   


二.节点相关   

      1.获取文档的根节点.   
            Element rootElm = document.getRootElement();   
      2.取得某节点的单个子节 点.   
            Element memberElm=root.element("member");// "member"是节点名   
      3.取得节点的文字   
            String text=memberElm.getText(); 也可以用:   
            String text=root.elementText("name");这个是取得根 节点下的name字节点的文字.   
      4.取得某节点下名为"member"的所有字节点并 进行遍历.   
            List nodes = rootElm.elements("member");   
            for (Iterator it = nodes.iterator(); it.hasNext();) {   
                  Element elm = (Element) it.next();   
                  // do something   
            }   
      5.对某节点下的所有子节点进 行遍历.   
             for(Iterator it=root.elementIterator();it.hasNext();){   
                  Element element = (Element) it.next();   
                   // do something   
            }   
      6.在某节点下添加子节 点.   
            Element ageElm = newMemberElm.addElement("age");   
      7.设置节点文字.   
            ageElm.setText("29");   
      8.删除某节点.   
            parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节 点   
      9. 添加一个CDATA节点.   
            Element contentElm = infoElm.addElement("content");   
            contentElm.addCDATA(diary.getContent());   

三. 属性相关.   

      1.取得某节点下的某属性   
            Element root=document.getRootElement();       
            Attribute attribute=root.attribute("size");// 属性名name
      2.取得属性的文字   
            // 也可以用
            String text=attribute.getText();   
            //  这个是取得根节点下name字节点的属性firstname的值:  
            String text2=root.element("name").attributeValue("firstname");
      3.遍历某节点的所有属 性    
            Element root=document.getRootElement();        
            for(Iterator it=root.attributeIterator();it.hasNext();){    
                 Attribute attribute = (Attribute) it.next();    
                 String text=attribute.getText();    
                 System.out.println(text);    
            }
      4.设置某节点的属性和文 字.    
            newMemberElm.addAttribute("name", "sitinspring");    
      5.设置属性的文字   
           Attribute attribute=root.attribute("name");    
           attribute.setText("sitinspring");    
      6.删除某属性    
           Attribute attribute=root.attribute("size");// 属性名name    
           root.remove(attribute);    

四.将文档写入XML文件.    
      
      1.文档中全为英文,不设置编 码,直接写入的形式.    
            XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));    
            writer.write(document);    
            writer.close();    
      2.文档中含有中文,设置编码 格式写入的形式.    
            OutputFormat format = OutputFormat.createPrettyPrint();    
            format.setEncoding("GBK");    // 指定XML编码            
            XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);                    
            writer.write(document);    
            writer.close();    

五.字符串与XML的转换    

      
1.将字符串转化为 XML    
            String text = "<members> <member>sitinspring</member> </members>";    
            Document document = DocumentHelper.parseText(text);    
      2.将文档或节点的XML转化 为字符串.    
            SAXReader reader = new SAXReader();    
            Document   document = reader.read(new File("input.xml"));                
            Element root=document.getRootElement();                    
            String docXmlText=document.asXML();    
            String rootXmlText=root.asXML();    
            Element memberElm=root.element("member");    
            String memberXmlText=memberElm.asXML();            

      清单 1. 示例 XML 文档(catalog.xml)     
            <?xml version="1.0" encoding="UTF-8"?>     
            <catalog>     
                  <!--An XML Catalog-->     
                  <?target instruction?>    
                  <journal title="XML Zone" publisher="IBM developerWorks">     
                        <article level="Intermediate" date="December-2001">    
                               <title>Java configuration with XML Schema</title>     
                               <author>     
                                     <firstname>Marcello</firstname>     
                                     <lastname>Vitaletti</lastname>     
                               </author>    
                         </article>    
                  </journal>     
            </catalog>      
      
      清单 2. 修改后的 XML 文档 (catalog-modified.xml)     
            <?xml version="1.0" encoding="UTF-8"?>     
            <catalog>     
                  <!--An XML catalog-->     
                  <?target instruction?>    
                  <journal title="XML Zone" publisher="IBM developerWorks">     
                        <article level="Introductory" date="October-2002">    
                              <title>Create flexible and extensible XML schemas</title>   
                              <author>     
                                    <firstname>Ayesha</firstname>     
                                    <lastname>Malik</lastname>     
                               </author>     
                        </article> 
                  </journal>
            </catalog>    

六.xpath语法

      XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。

路 径表达式结果
/bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()<3] 选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang] 选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang='eng'] 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00] 选取所有 bookstore 元素的 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title 选取所有 bookstore 元素中的 book 元素的 title 元素,且其中的 price 元素的值须大于 35.00。

 

通配符描述
* 匹配任何元素节点
@* 匹配任何属性节点
node() 匹配任何类型的节点

 

轴名称结果
ancestor 选取当前节点的所有先辈(父、祖父等)
ancestor-or-self 选取当前节点的所有先辈(父、祖父等)以及当前节点本身
attribute 选 取当前节点的所有属性
child 选取当前节点的所有子元素。
descendant 选取当前节点的所有后代元素(子、孙等)。
descendant-or-self 选取当前节点的所有后代元素(子、孙等)以及当前节点本身。
following 选 取文档中当前节点的结束标签之后的所有节点。
namespace 选取当前节点的所有命名 空间节点
parent 选取当前节点的父节点。
preceding 选取文档中当前节点的开始标签之前的所有节点。
preceding-sibling 选 取当前节点之前的所有同级节点。
self 选取当前节点。

 

例子结果
child::book 选取所有属于当前节点的子元素的 book 节点
attribute::lang 选 取当前节点的 lang 属性
child::* 选取当前节点的所有子元素
attribute::* 选取当前节点的所有属性
child::text() 选取当前节点的所有文本子节点
child::node() 选取当前节点的所有 子节点
descendant::book 选取当前节点的所有 book 后代
ancestor::book 选择当前节点的所有 book 先辈
ancestor-or-self::book 选取当前节点的所有book先辈以及当前节点(假如此节点是book节点的 话)
child::*/child::price 选取当前节点的所有 price 孙。
posted @ 2012-12-25 19:02  subsir  阅读(257)  评论(0编辑  收藏  举报