DOM4J 知识详解

一.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");// 创建根节点,只有空DOCUMENT对象才能创建ROOT结点


二.节点控制

1.获取文档的根节点.
           Element   root = document.getRootElement();
2.取得节点的文本
           String text=memberElm.getText();
也可以用:
           String text=root.elementText("name");   //这个是取得根节点下的name字节点的文字;可以类推任何节点下的文本
3.设置节点文字.
           ageElm.setText("29");
4.父节点下获得单个子节点对象.
           Element memberElm=root.element("member");  // "member"是节点名

5.取得父节点下遍历名为"member"的所有子节点.
           List nodes = rootElm.elements("member");
           for (Iterator it = nodes.iterator(); it.hasNext();) {
                 Element elm = (Element) it.next();
                 // do something
            }
6.父节点下的遍历所有子节点进行.
            for(Iterator it=root.elementIterator();it.hasNext();){
                Element element = (Element) it.next();
                // do something
            }
7.父节点下添加子节点.
           Element ageElm = newMemberElm.addElement("age");

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");
     //Element nodes0=xmlDoc.selectSingleNode("/bookstore"); //采用相对路径,即当前结点(包括当前结点)开始查找,与下列结果相同.
     //Element nodes=nodes0.selectNodes("book");      ////采用绝对路径,即当前结点(包括当前结点)开始查找,
     //XPATH语法详见: http://www.w3school.com.cn/xpath/xpath_syntax.asp


      Iterator it=projects.iterator();
      
      while(it.hasNext()){
        Element elm=(Element)it.next();       
        System.out.println(elm.getText());
      }
      
    }
    catch(Exception ex){
       ex.printStackTrace();
    }
  }

你可能感兴趣的:(dom4j)