xml解析dom4j

dom4j解析xml;
*查询所有name元素里面的值
1、创建解析器
2、得到document
3、得到所有的p1标签
element(qname)获取标签下面的第一个子标签   qname:标签名称
elements(qname)获取标签下面的所有子标签(一层)
elements()获取标签下面的所有一层子标签
4、得到name
5、得到name里面的值
*dom4j支持xpath的操作
1、直接获取到某个元素
2、第一种形式 /aaa/ddd/ccc :表示得到一层中的aaa下的ddd下的ccc元素
3、第二种形式//aaa:表示只要是aaa都得到
3、第三种形式/*:得到所有标签
4、第四种形式/aaa/ddd[1]:表示aaa下面第一个ddd元素       /aaa[last()]:表示最后一个aaa标签
5、第五种形式://aaa[@id] :得到所有有id属性的aaa标签
6、第六种形式://aaa[@name='user']得到所有name属性值为user的aaa标签

<?xml version="1.0" encoding="UTF-8"?>

<person> 
  <p1 id='person'> 
    <name>张三</name>  
    <sex>nan</sex>  
    <sex>nan</sex>  
    <sex>nan</sex> 
  </p1>  
  <school>三中</school>  
  <school>三中</school>  
  <p1> 
    <name>李四</name>  
    <age>24</age> 
  </p1>  
  <p1> 
    <name>王五</name>  
    <age>25</age> 
  </p1> 
</person>
package cn.code.dom4j;

import java.io.FileOutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

import cn.code.dom4jUtils.Dom4jUtils;

/**
 * dom4j不是javase的一部分,需要先导包;
 * Dom4j会先创建一个dom树,然后逐行解析,sax,dom集于一身,所以可以实现增删改查;
 * SAXReeader解析器 是类可以直接new
 * Document是xml文档对象 是接口父接口是Nodes
 * getRootElements();返回根节点,返回值是Element类型,Element是Nodes的子接口;
 * */
public class Dom4j_01 {
    @Test
    public void test1()throws Exception{
        SAXReader r = new SAXReader();
        Document d = r.read("src/cn/code/dom4j/Person.xml");
        Element root = d.getRootElement();
        List<Element>list = root.elements("p1");
        for(Element p1:list){
            Element name = p1.element("name");
            String s =name.getText();
            System.out.println(s);
        }
    }
    @Test
    //在p1标签末尾添加标签
    public void test2()throws Exception{
        SAXReader r = new SAXReader();
        Document d = r.read("src/cn/code/dom4j/Person.xml");
        Element root = d.getRootElement();
        Element p1 = root.element("p1");
        Element sex = p1.addElement("sex");
         sex.setText("nan");
         OutputFormat format = OutputFormat.createPrettyPrint();
         XMLWriter xmlwriter = new XMLWriter(new FileOutputStream("src/cn/code/dom4j/Person.xml"),format);
         xmlwriter.write(d);
         xmlwriter.close();
    }
    //在任意位置创建标签
    @Test
    public void test3()throws Exception{
        SAXReader r = new SAXReader();
        Document d = r.read("src/cn/code/dom4j/Person.xml");
        Element root = d.getRootElement();
        Element p1 = root.element("p1");
        //创建school标签
        Element school = DocumentHelper.createElement("school");
        school.setText("三中");
        List<Element> list = p1.elements();
        list.add(1, school);
        //回写xml
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlwriter = new XMLWriter(new FileOutputStream("src/cn/code/dom4j/Person.xml"),format);
        xmlwriter.write(d);
        xmlwriter.close();
    }
    //修改指定标签内容
    @Test
    public void test4()throws Exception{
        Document d = Dom4jUtils.getDocument("src/cn/code/dom4j/Person.xml");
        Element root =d.getRootElement();
        Element p1 = root.element("p1");
        Element age = p1.element("age");
        age.setText("22");
        Dom4jUtils.xmlWriterBack("src/cn/code/dom4j/Person.xml", d);
    }
    @Test
    //删除指定标签
    public void test5(){
        Document d = Dom4jUtils.getDocument("src/cn/code/dom4j/Person.xml");
        Element p1= d.getRootElement().element("p1");
        Element age = p1.element("age");
        p1.remove(age);
        Dom4jUtils.xmlWriterBack("src/cn/code/dom4j/Person.xml", d);
    }
    @Test
    public void  test6(){
        Document d = Dom4jUtils.getDocument("src/cn/code/dom4j/Person.xml");
        Element p1 = d.getRootElement().element("p1");
        //获取属性值
        String s = p1.attributeValue("id");
        System.out.println(s);
    }
    //使用xpath完成定位标签以及属性
    @Test
    public void test7(){
        Document d = Dom4jUtils.getDocument("src/cn/code/dom4j/Person.xml");
        List<Node> list = d.selectNodes("//p1/name");
        for (Node node : list) {
            String s = node.getText();
            System.out.println(s);
        }
    }
    @Test
    public void test8(){
        Document d = Dom4jUtils.getDocument("src/cn/code/dom4j/Person.xml");
        Node name = d.selectSingleNode("//p1[@id='person']/name");
        String s = name.getText();
        System.out.println(s);
    }
}

工具类

package cn.code.dom4jUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

public class Dom4jUtils {
    public static Document getDocument(String path){
        //获取解析器
        SAXReader r = new SAXReader();
        try {
            Document d = r.read(path);
            return d;
        } catch (DocumentException e) {
            throw new RuntimeException();
        }
    }
    public static void xmlWriterBack(String path,Document document) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlwriter = null;
        try {
             xmlwriter = new XMLWriter(new FileOutputStream(path),format);
            xmlwriter.write(document);
            
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                xmlwriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 

package cn.itcast.dom4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

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;

public class TestDom4j {

    public static void main(String[] args) throws DocumentException, IOException,Exception {
//        selectFirstNameValue();
//        insertElement();
//        insertElement_2();
//        modifyElementText();
//        removeElement();
        getAttributeValue();
    }
    public static void getAttributeValue()throws Exception {
        // 获取name id属性的值
        SAXReader sax = new SAXReader();
        Document document = sax.read("src/person.xml");
        Element root = document.getRootElement();
        Element p1 = root.element("p1");
        Element name = p1.element("name");
        String str = name.attributeValue("id");
        System.out.println(str);
    }
    public static void removeElement() throws DocumentException ,Exception{
        // 删除第一个p1下的school节点
        SAXReader sax = new SAXReader();
        Document document = sax.read("src/person.xml");
        Element root = document.getRootElement();
        Element p1 = root.element("p1");
        Element school = root.element("p1").element("school");
        //通过父节点删除school节点
        p1.remove(school);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlwriter = new XMLWriter(new FileOutputStream("src/person.xml"),format);
        xmlwriter.write(document);
        xmlwriter.close();
    }
    public static void modifyElementText() throws DocumentException, IOException {
        // TODO Auto-generated method stub
        SAXReader sax = new SAXReader();
        Document document = sax.read("src/person.xml");
        Element root = document.getRootElement();
        root.element("p1").element("age").setText("30");
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlwriter = new XMLWriter(new FileOutputStream("src/person.xml"),format);
        xmlwriter.write(document);
        xmlwriter.close();
    }
    public static void insertElement_2() throws DocumentException, IOException {
        // 特定位置插入节点
        SAXReader sax = new SAXReader();
        Document document = sax.read("src/person.xml");
        Element root = document.getRootElement();
        List<Element> e = root.element("p1").elements();
        //创建school元素
        Element school = DocumentHelper.createElement("school");
        //添加文本内容
        school.setText("三中");
        e.add(1, school);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlwriter = new XMLWriter(new FileOutputStream("src/person.xml"),format);
        xmlwriter.write(document);
        xmlwriter.close();
    }
    public static void insertElement() throws DocumentException, IOException {
        // TODO Auto-generated method stub
        SAXReader sax = new SAXReader();
        Document document = sax.read("src/person.xml");
        Element root = document.getRootElement();
        Element sex = root.element("p1").addElement("sex");
        sex.setText("gril");
        //回写
        OutputFormat format = OutputFormat.createPrettyPrint();//漂亮的格式
        XMLWriter xmlwriter =  new XMLWriter(new FileOutputStream("src/person.xml"),format);
        xmlwriter.write(document);
        xmlwriter.close();
    }
    public static void selectNameValue() throws DocumentException{
                //创建解析器
                SAXReader saxReader = new SAXReader();
                //得到document
                Document  document = saxReader.read("src/person.xml");
                //得到根节点
                Element root  = document.getRootElement();
                //得到p1
                List<Element> p1 = root.elements("p1");
                //遍历p1得到下面的name
                for(Element  element : p1){
                    String str =element.element("name").getText();
                    System.out.println(str);
                }
    }
    public static void selectFirstNameValue() throws DocumentException{
        SAXReader  sr = new SAXReader();
        Document document = sr.read("src/person.xml");
        String str = document.getRootElement().element("p1").element("name").getText();
        System.out.println(str);
    }

}

 

转载于:https://www.cnblogs.com/wangyinxu/p/7402312.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值