Dom解析

一.xml两种解析方式:

1.DOM解析

  (1)JAXP oracle-Sun公司官方)

  (2)JDOM工具(非官方)

  (3)Dom4J工具(非官方)

  三大框架(默认读取xml的工具就是Dom4j

  .......

2.SAX解析

  (1)Sax解析工具(oracle-sun公司官方)

Dom解析原理:

  xml解析器一次性把整个xml文档加载进内存,然后在内存中构建一颗Document的对象树,通过  Document对象,得到树上的节点对象,通过节点对象访问(操作)到xml文档的内容。

Dom4j工具:

  非官方,不在jdk中。

  使用步骤:

  (1)导入dom4j的核心包。 dom4j-1.6.1.jar

  (2)编写Dom4j读取xml文件代码

  读取xml文件代码:

package com.dom4j.xml_red;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class xml_read {

    public static void main(String[] args) {
        
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File("./src/contact.xml"));
            System.out.println(doc);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
View Code

使用Dom4j读取xml文件常用方法:

  1.节点:

  Iterator  Element.nodeIterator();  //获取当前标签节点下的所有子节点

  2.标签:

   Element  Document.getRootElement();  //获取xml文档的根标签

   Element   ELement.element("标签名") //指定名称的第一个子标签

   Iterator<Element> Element.elementIterator("标签名");// 指定名称的所有子标签  

   List<Element>  Element.elements(); //获取所有子标签

  3.属性:

  String   Element.attributeValue("属性名") //获取指定名称的属性值

  Attribute    Element.attribute("属性名")//获取指定名称的属性对象

  Attribute.getName()  //获取属性名称

  Attibute.getValue()  //获取属性值

  List<Attribute>  Element.attributes();  //获取所有属性对象

  Iterator<Attribute> Element.attibuteIterator(); //获取所有属性对象

  4.文本:

  Element.getText();  //获取当前标签的文本

  Element.elementText("标签名") //获取当前标签的指定名称的子标签的文本内容

   方法练习读取xml文件全部使其显示代码:

package com.dom4j.xml_red;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.Attribute;
import org.dom4j.io.SAXReader;
import org.junit.Test;





public class getNode {
    
    
    public static void test1() throws Exception{
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("./src/contact.xml"));
        Iterator<Node> it = doc.nodeIterator();
        while(it.hasNext()){
            Node node = it.next();
            System.out.println(node.getName());
        }
    }
    
    public static void test2() throws Exception{
        //获取属性
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("./src/contact.xml"));
        Element contactElem = doc.getRootElement().element("contact");
        String value = contactElem.attributeValue("id");
        System.out.println(value);
        
        List<Attribute> list = contactElem.attributes();
        
        for(Attribute attr : list){
            System.out.println(attr.getName() + " = " + attr.getValue());
        }
        
        
        
    }
    private static void getChild(Element ele){
        //获取所有节点
        System.out.println(ele.getName());
        Iterator<Node> it = ele.nodeIterator();
        while(it.hasNext()){
            Node node = it.next();
            if(node instanceof Element){
                getChild((Element)node);
            }
        }
    }
    
    private static void test3() throws Exception{
        //获取文本;
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("./src/contact.xml"));
        
        Element nameElem = 
            doc.getRootElement().element("contact").element("name");
        String text = nameElem.getText();
        System.out.println(text);
        
        System.out.println(doc.getRootElement().element("contact").elementText("phone"));
    }
    
    public static void main(String[] args) throws Exception{
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("./src/contact.xml"));
        //getChild(doc.getRootElement());
//        Element rootEle = doc.getRootElement();
//        List<Element> list = rootEle.elements();
//        for(Element e : list){
//            System.out.println(e.getName());
//        }
        
        //test3();
        StringBuffer sb = new StringBuffer();
        getChildNodes(doc.getRootElement(), sb);
        System.out.println(sb);
        
    }
    
    private static void getChildNodes(Element ele, StringBuffer sb){
        sb.append("<" + ele.getName());
        //System.out.println(ele.getName());
        //获取属性
        List<Attribute> attributesList = ele.attributes();
        for(Attribute attr : attributesList){
            //System.out.println(attr.getName());
            sb.append(" " + attr.getName() + "=" + "\"" + attr.getValue() + "\"");
        }
        sb.append(">");
        //获取文本
        sb.append(ele.getText());
        //获取子节点
        List<Element> elementsList = ele.elements();
        for(Element elem : elementsList){
            getChildNodes(elem, sb);
        }
//        Iterator<Element>it = ele.elementIterator();
//        while(it.hasNext()){
//            Element elenode = it.next();
//            if(elenode instanceof Element){
//                getChildNodes(elenode);
//            }
//        }
        sb.append("<" + ele.getName() + ">");
    }
    
    
}
View Code

  定义类读取xml文件内容

  定义类:

package com.dom4j.xml_red;

public class Contact {

    private String id;
    private String name;
    private String age;
    private String phone;
    private String email;
    private String qq;
    @Override
    public String toString() {
        return "Contact [id=" + id + ", name=" + name + ", age=" + age
                + ", phone=" + phone + ", email=" + email + ", qq=" + qq + "]";
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getQq() {
        return qq;
    }
    public void setQq(String qq) {
        this.qq = qq;
    }
    
}
View Code

  读取内容放入上面的类:

package com.dom4j.xml_red;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

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

public class PackUpContact {

    
    public static void main(String[] args) throws Exception {
        ArrayList<Contact> arrayList = new ArrayList<Contact>();
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("./src/contact.xml"));
        //读取contact
        Iterator<Element> elementIterator = doc.getRootElement().elementIterator("contact");
        while(elementIterator.hasNext()){
            Element elem = elementIterator.next();
            Contact contact = new Contact();
            contact.setId(elem.attributeValue("id"));
            contact.setName(elem.elementText("name"));
            contact.setAge(elem.elementText("age"));
            contact.setPhone(elem.elementText("phone"));
            contact.setEmail(elem.elementText("email"));
            contact.setQq(elem.elementText("qq"));
            arrayList.add(contact);
        }
        for(Contact contact : arrayList){
            System.out.println(contact);
        }
        
    }

}
View Code

   修改xml:

增加:

  DocumentHelper.createDocument()  增加文档

  addElement("名称")  增加标签

  addAttribute("名称",“值”)  增加属性

修改:

  Attribute.setValue("")  修改属性值

  Element.addAtribute("同名的属性名","")  修改同名的属性值

  Element.setText("内容")  修改文本内容

删除

  Element.detach();  删除标签  

  Attribute.detach();  删除属性

代码:

 

package com.dom4j.xml_writer;

import java.io.FileOutputStream;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.DocumentHandler;


public class xml_writer {
    
    public static void main(String[] args) throws Exception {
        /*
        //读
        //Document doc = new SAXReader().read("./src/contact.xml");
        Document doc = DocumentHelper.createDocument();
        Element rootElement = doc.addElement("contactList");
        Element contactElement = rootElement.addElement("contact");
        contactElement.addElement("name");
        
        contactElement.addAttribute("id", "001");
        contactElement.addAttribute("name", "eric");
        //写
        OutputFormat format = OutputFormat.createPrettyPrint();
        FileOutputStream out = new FileOutputStream("E:/Test/1.xml");
        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(doc);
        writer.close();
        */
        Delect();
    }
    
    public static void Alter() throws Exception{
        Document doc = new SAXReader().read("E:/Test/1.xml");
        Element contactElem = doc.getRootElement().element("contact");
        
        Attribute idAttr = contactElem.attribute("id");
        idAttr.setValue("003");
        
        OutputFormat format = OutputFormat.createPrettyPrint();
        FileOutputStream out = new FileOutputStream("E:/Test/1.xml");
        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(doc);
        writer.close();
    }
    
    public static void Delect() throws Exception{
        Document doc = new SAXReader().read("E:/Test/1.xml");
        Element contactElem = doc.getRootElement().element("contact");
        
        contactElem.detach();
        
        OutputFormat format = OutputFormat.createPrettyPrint();
        FileOutputStream out = new FileOutputStream("E:/Test/1.xml");
        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(doc);
        writer.close();
    }
    
}

 

posted @ 2016-11-04 22:13  handsomecui  阅读(359)  评论(0编辑  收藏  举报