`
simple_hui
  • 浏览: 156858 次
  • 性别: Icon_minigender_2
  • 来自: 武汉
社区版块
存档分类
最新评论

java dom4j操作xml

阅读更多

这是从网上找来的解析xml的文章

SAXReader reader = new SAXReader();    
Document doc = reader.read(...);    
List childNodes = doc.selectNodes("//Config/Child/ChildNode");    
for(Object obj:childNodes) {    
      Node childNode = (Node)obj;    
      S
tring name = childNode.valueOf("@name");    
      
String text = childNode.getText();    
}      

一.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();      


      {    
dom4j API 包含一个解析 XML 文档的工具。本文中将使用这个解析器创建一个示例 XML 文档。清单 1 显示了这个示例 XML 文档,catalog.xml。   } 

      
      清单 
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>      

            
            然后使用同一个解析器修改 catalog.xml,清单 2 是修改后的 XML 文档,catalog-modified.xml。    
      
      清单 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>    

                  与 W3C DOM API 相比,使用 dom4j 所包含的解析器的好处是 dom4j 拥有本地的 XPath 支持。DOM 解析器不支持使用 XPath 选择节点。    


      本文包括以下几个部分:   

  1. 预先设置    
  2. 创建文档    
  3. 修改文档    

      预先设置   

             这个解析器可以从 http://dom4j.org 获取。通过设置使 dom4j-1.4/dom4j-full.jar 能够在 classpath 中访问,该文件中包括 dom4j 类、XPath 引擎以及 SAX 和 DOM 接口。如果已经使用了 JAXP 解析器中包含的 SAX 和 DOM 接口,向 classpath 中增加 dom4j-1.4/dom4j.jar 。 dom4j.jar 包括 dom4j 类和 XPath 引擎,但是不含 SAX 与 DOM 接口。    

      创建文档   

            本节讨论使用 dom4j API 创建 XML 文档的过程,并创建示例 XML 文档 catalog.xml。    
            
            使用 import 语句导入 dom4j API 类:    
            
            import org.dom4j.Document;    
            import org.dom4j.DocumentHelper;    
            import org.dom4j.Element;     

            使用 DocumentHelper 类创建一个文档实例。 DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类。           
            Document document = DocumentHelper.createDocument();     
            
            使用 addElement() 方法创建根元素 catalog 。 addElement() 用于向 XML 文档中增加元素。     
            Element catalogElement = document.addElement("catalog");    

            在 catalog 元素中使用 addComment() 方法添加注释“An XML catalog”。     
            catalogElement.addComment("An XML catalog");    

            在 catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令。     
            catalogElement.addProcessingInstruction("target","text");     
            
            在 catalog 元素中使用 addElement() 方法增加 journal 元素。     
            Element journalElement =  catalogElement.addElement("journal");    

            使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性。     
            journalElement.addAttribute("title""XML Zone");    
            journalElement.addAttribute("publisher""IBM developerWorks");     
            
            向 article 元素中添加 journal 元素。    
            
Element articleElement=journalElement.addElement("article");    

            为 article 元素增加 level 和 date 属性。     
            articleElement.addAttribute("level""Intermediate");    
            articleElement.addAttribute("date""December-2001");     
            向 article 元素中增加 title 元素。     
            Element titleElement=articleElement.addElement("title");    

            使用 setText() 方法设置 article 元素的文本。     
            titleElement.setText("Java configuration with XML Schema");     
            在 article 元素中增加 author 元素。     
            Element authorElement=articleElement.addElement("author");     
            在 author 元素中增加 firstname 元素并设置该元素的文本。     
            Element  firstNameElement=authorElement.addElement("firstname");    
            firstNameElement.setText("Marcello");     
            在 author 元素中增加 lastname 元素并设置该元素的文本。    
            
Element lastNameElement=authorElement.addElement("lastname");    
            lastNameElement.setText("Vitaletti");     
            可以使用 addDocType() 方法添加文档类型说明。    
            
document.addDocType("catalog"null,"file://c:/Dtds/catalog.dtd");     
            这样就向 XML 文档中增加文档类型说明:  
            
<!DOCTYPE catalog SYSTEM "file://c:/Dtds/catalog.dtd">    

      
          
  如果文档要使用文档类型定义(DTD)文档验证则必须有 Doctype。    
      
            XML 声明 <?xml version="1.0" encoding="UTF-8"?> 自动添加到 XML 文档中。     
            
            清单 3 所示的例子程序 XmlDom4J.java 用于创建 XML 文档 catalog.xml。    
            清单 3. 生成 XML 文档 catalog.xml 的程序(XmlDom4J.java)           
            import org.dom4j.Document;    
            import org.dom4j.DocumentHelper;    
            import org.dom4j.Element;    
            import org.dom4j.io.XMLWriter;    
            import java.io.*;    
            public class XmlDom4J{    
                  public void generateDocument(){    
                        Document document = DocumentHelper.createDocument();    
                        Element catalogElement = document.addElement("catalog");    
                        catalogElement.addComment("An XML Catalog");    
                        catalogElement.addProcessingInstruction("target","text");    
                        Element journalElement =  catalogElement.addElement("journal");    
                        journalElement.addAttribute("title""XML Zone");    
                        journalElement.addAttribute("publisher""IBM developerWorks");    
                        Element articleElement=journalElement.addElement("article");    
                        articleElement.addAttribute("level""Intermediate");   
                        articleElement.addAttribute("date""December-2001");
                        
Element  titleElement=articleElement.addElement("title");   
                        titleElement.setText("Java configuration with XML Schema");
                        Element authorElement=articleElement.addElement("author");
                        Element  firstNameElement=authorElement.addElement("firstname");    
                        firstNameElement.setText("Marcello");
                        
Element lastNameElement=authorElement.addElement("lastname");   
                        lastNameElement.setText("Vitaletti");
                        
document.addDocType("catalog",  null,"file://c:/Dtds/catalog.dtd");
                        try{   
                              XMLWriter output = new XMLWriter(new FileWriter( new File("c:/catalog/catalog.xml") ));    
                              output.write( document );    
                              output.close();    
                        }catch(IOException e){
                              System.out.println(e.getMessage());
                        }   
 
                  }    
                  public static void main(String[] argv){    
                        XmlDom4J dom4j=new XmlDom4J();    
                        dom4j.generateDocument();    
                  }
            }   
 


            这一节讨论了创建 XML 文档的过程,下一节将介绍使用 dom4j API 修改这里创建的 XML 文档。    

            
      修改文档   
 
            
                  这一节说明如何使用 dom4j API 修改示例 XML 文档 catalog.xml。   


      使用 SAXReader 解析 XML 文档 catalog.xml:   
 
            SAXReader saxReader = new SAXReader();   
            
Document document = saxReader.read(inputXml);     
      
      SAXReader 包含在 org.dom4j.io 包中。     
            inputXml 是从 c:/catalog/catalog.xml 创建的 java.io.File。使用 XPath 表达式从 article 元素中获得 level 节点列表。如果 level 属性值是“Intermediate”则改为“Introductory”。     
            
            List list = document.selectNodes("//article/@level" );    
            Iterator iter=list.iterator();    
            while(iter.hasNext()){    
                  Attribute attribute=(Attribute)iter.next();    
                  if(attribute.getValue().equals("Intermediate"))    
                        attribute.setValue("Introductory");     
                  }     

            获取 article 元素列表,从 article 元素中的 title 元素得到一个迭代器,并修改 title 元素的文本。    

                  list = document.selectNodes("//article" );    
                  iter=list.iterator();    
                  while(iter.hasNext()){    
                        Element element=(Element)iter.next();    
                        Iterator iterator=element.elementIterator("title");    
                        while(iterator.hasNext()){    
                              Element titleElement=(Element)iterator.next();    
                              if(titleElement.getText().equals("Java configuration with XML Schema"))    
                                   titleElement.setText("Create flexible and extensible XML schema");    
                        }
                  }    

   

        通过和 title 元素类似的过程修改 author 元素。    


      清单 
4 所示的示例程序 Dom4JParser.java 用于把 catalog.xml 文档修改成 catalog-modified.xml 文档。    
      清单 4. 用于修改 catalog.xml 的程序(Dom4Jparser.java)     
      
            import org.dom4j.Document;    
            import org.dom4j.Element;    
            import org.dom4j.Attribute;    
            import java.util.List;    
            import java.util.Iterator;    
            import org.dom4j.io.XMLWriter;    
            import java.io.*;    
            import org.dom4j.DocumentException;    
            import org.dom4j.io.SAXReader;     
            public class Dom4JParser{    
                  public void modifyDocument(File inputXml){    
                  try{    
                        SAXReader saxReader = new SAXReader();    
                        Document document = saxReader.read(inputXml);    
                        List list = document.selectNodes("//article/@level" );    
                        Iterator iter=list.iterator();    
                        while(iter.hasNext()){    
                              Attribute attribute=(Attribute)iter.next();    
                              if(attribute.getValue().equals("Intermediate"))    
                              attribute.setValue("Introductory");     
                        }    
                        list = document.selectNodes("//article/@date" );    
                        iter=list.iterator();    
                        while(iter.hasNext()){    
                              Attribute attribute=(Attribute)iter.next();    
                              if(attribute.getValue().equals("December-2001"))    
                              attribute.setValue("October-2002");    
                        }    
                        list = document.selectNodes("//article" );    
                        iter=list.iterator();    
                        while(iter.hasNext()){    
                              Element element=(Element)iter.next();    
                              Iterator iterator=element.elementIterator("title");    
                              while(iterator.hasNext()){    
                                    Element titleElement=(Element)iterator.next();    
                                    if(titleElement.getText().equals("Java configuration with XML Schema"))    
                                          titleElement.setText("Create flexible and extensible XML schema");    
                                    }    
                              }    
                              list = document.selectNodes("//article/author" );    
                              iter=list.iterator();    
                              while(iter.hasNext()){    
                                    Element element=(Element)iter.next();    
                                    Iterator iterator=element.elementIterator("firstname");    
                                    while(iterator.hasNext()){    
                                          Element firstNameElement=(Element)iterator.next();    
                                          if(firstNameElement.getText().equals("Marcello"))    
                                                firstNameElement.setText("Ayesha");   
                                    
}
                              }    
                              list = document.selectNodes("//article/author" );    
                              iter=list.iterator();    
                              while(iter.hasNext()){    
                                    Element element=(Element)iter.next();    
                                    Iterator iterator=element.elementIterator("lastname");    
                                    while(iterator.hasNext()){    
                                          Element lastNameElement=(Element)iterator.next();    
                                          if(lastNameElement.getText().equals("Vitaletti"))    
                                                lastNameElement.setText("Malik");    
                                    }  
                              }    
                              XMLWriter output = new XMLWriter( new FileWriter( new File("c:/catalog/catalog-modified.xml") ));    
                              output.write( document ); 
                              
output.close();    
                        catch(DocumentException e) {    
                              System.out.println(e.getMessage());    
                        } catch(IOException e){   
                             
 System.out.println(e.getMessage());    
                        }    
                  }    
                  
                  public static void main(String[] argv){    
                        Dom4JParser dom4jParser=new Dom4JParser();    
                        dom4jParser.modifyDocument(new File("c:/catalog/catalog.xml"));    
                  }    
            }   

分享到:
评论
2 楼 simple_hui 2012-03-29  
a114d 写道
楼主,创建xml的过程没看懂,这句
XMLWriter output = new XMLWriter(new FileWriter( new File("c:/catalog/catalog.xml") ));
不是要创建这个名字的xml文件吗?怎么直接写入了呢?

我也不是很明白你的意思
先创建这个文件,然后往这个文件写内容。
1 楼 a114d 2012-03-15  
楼主,创建xml的过程没看懂,这句
XMLWriter output = new XMLWriter(new FileWriter( new File("c:/catalog/catalog.xml") ));
不是要创建这个名字的xml文件吗?怎么直接写入了呢?

相关推荐

Global site tag (gtag.js) - Google Analytics