dom4j 最常用最简单的用法(转)

要使用dom4j读写XML文档,需要先下载dom4j包,dom4j官方网站在 http://www.dom4j.org/
目前最新dom4j包下载地址:http://nchc.dl.sourceforge.net/sourceforge/dom4j/dom4j-1.6.1.zip

解开后有两个包,仅操作XML文档的话把dom4j-1.6.1.jar加入工程就可以了,如果需要使用XPath的话还需要加入包jaxen-1.1-beta-7.jar.

以下是相关操作:

一.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是其父节点
三.属性相关.
1.取得某节点下的某属性
            Element root=document.getRootElement();    
            Attribute attribute=root.attribute("size");// 属性名name
2.取得属性的文字
            String text=attribute.getText();
也可以用:
String text2=root.element("name").attributeValue("firstname");这个是取得根节点下name字节点的属性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();
六.使用XPath快速找到节点.
读取的XML文档示例
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
  <name>MemberManagement</name>
  <comment></comment>
  <projects>
    <project>PRJ1</project>
    <project>PRJ2</project>
    <project>PRJ3</project>
    <project>PRJ4</project>
  </projects>
  <buildSpec>
    <buildCommand>
      <name>org.eclipse.jdt.core.javabuilder</name>
      <arguments>
      </arguments>
    </buildCommand>
  </buildSpec>
  <natures>
    <nature>org.eclipse.jdt.core.javanature</nature>
  </natures>
</projectDescription>

使用XPath快速找到节点project.
 public static void main(String[] args){
    SAXReader reader = new SAXReader();
    
    try{
      Document  doc = reader.read(new File("sample.xml"));
      
      List projects=doc.selectNodes("/projectDescription/projects/project");
      
      Iterator it=projects.iterator();
      
      while(it.hasNext()){
        Element elm=(Element)it.next();       
        System.out.println(elm.getText());
      }
      
    }
    catch(Exception ex){
       ex.printStackTrace();
    }

附带一个简单的例子

package com.stz;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;

import java.util.Iterator;
import java.util.List;

public class TestDate {

  public static void  main(String[]args){
    String xml="<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
     "<students>"+
     "   <student id=\"1\">"+
      "      <name>stz</name>"+
       "     <age>23</age>"+
        "</student>"+
        "<student id=\"2\">"+
            "<name>rhl</name>"+
            "<age>23</age>"+
        "</student>"+
        "<student id=\"3\">"+
         "   <name>tom</name>"+
          "  <age>23</age>"+
        "</student>"+
    "</students>";   
    
    try {
        Document document=DocumentHelper.parseText(xml);
        Element root=document.getRootElement();
        //System.out.println(ele.e);
        //List nodes=root.elements("student");
        //System.out.println(root.getName());
        //root.elementIterator();
        List nodes=document.selectNodes("/students/student");

        for (Iterator it = nodes.iterator(); it.hasNext();) {
            Element elm = (Element) it.next();
            System.out.println("id:"+elm.attributeValue("id"));
            System.out.println(elm.getName());
            Element eles=elm.element("name");
            System.out.println(eles.getText());
            Element elea=elm.element("age");
            System.out.println(elea.getText());
         }

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    
    

  }
}

 

你可能感兴趣的:(dom4j如何读写XML,dom4j的用法,java如何读写XML)