XML之------dom4j对XML文档增删改查

时间:2022-10-21 07:55:13

用dom4j对xml文档进行操作实例

可以对xml文档进行增删改查操作

和dom不同的是,因为dom4j是第三方的,因此需要进行build path操作

首先需要使用反编译软件将dom4j中所有的包打包成jar包放到项目的根目录去(最好在根目录中新建一个lib文件夹放里面去,因为后面还要用到一个dom4j的依赖包也要放到这里面来),然后在myEclipse中右键点击jar包会出现一个build path,点击即可。

在你自己的第三方文件dom4j中的lib文件夹下有一个名为jaxen-1.1-beta-6.jar的包,同样也放到jar包dom4j-1.6.1.jar相同的的目录下,再用上述相同的方法build path即可

实例:

Dom4jDemo.java

package cn.hncu.dom4j;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
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.junit.Test;

public class Dom4jDemo {
	@Test
    public void readDemo() throws Exception{
    	//声明SAXReader核心读取(xml)类,并获得dom对象
		SAXReader sax = new SAXReader();
    	Document dom = sax.read("./xml5/users.xml");
    	//获取根元素
    	Element root = dom.getRootElement();
    	//获取里面的第一个子元素
    	Element user = root.element("user");
    	String id = user.attributeValue("id");
    	System.out.println(id);
    	String name = user.element("name").getText();//获取子元素中的文本内容--法1
    	String age = user.elementText("age");//获取子元素中的文本内容--法2
    	System.out.println(name+","+age);
    }
	
	//显示(遍历)所有的用户
	@Test
    public void readAll() throws Exception{
		SAXReader reader = new SAXReader();
        Document document = reader.read("./xml5/users.xml");
        Element root = document.getRootElement();
        Iterator<Element> it = root.elementIterator(); 
        while(it.hasNext()){
        	Element e = it.next();
        	String id = e.attributeValue("id");
        	String name = e.element("name").getText();
        	String age = e.elementText("age");
        	System.out.println("id:"+id+",name:"+name+",age:"+age);
        }
    }
	
	//添加一个<user>元素
	@Test
    public void addElement() throws Exception{
		SAXReader reader = new SAXReader();
        Document document = reader.read("./xml5/users.xml");
        Element root = document.getRootElement();
        
        Element e = root.addElement("user");
        e.addAttribute("id", "C003");
        Element eName = e.addElement("name");
        eName.setText("玛丽");
        Element eAge = e.addElement("age");
        eAge.setText("24");
        
        //要把内存中的dom对象写到目的地(磁盘)
        //法1---功能有限
//        FileWriter fw = new FileWriter("./xml5/users.xml");
//        document.write(fw);
//        fw.close();
        //法2---功能更强
        //XMLWriter writer = new XMLWriter( System.out );//输出到控制台
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(new FileWriter("./xml5/users.xml"),format );//以指定的输出格式,把dom输出到指定的目的地(文件)
        writer.write(document);
        writer.close();
        
	}
	
	//删除最后一个<user>元素
	@Test
    public void delElement() throws Exception{
		SAXReader reader = new SAXReader();
        Document document = reader.read("./xml5/users.xml");
        Element root = document.getRootElement();
        
        List<Element> list = root.elements();
        Element e = list.get(list.size()-1);
        e.getParent().remove(e);
        
        //保存
        XMLWriter writer = new XMLWriter(new FileOutputStream("./xml5/users.xml"));
        writer.write(document);
        writer.close();
	}
	
	//从零开始创建一个xml文档
	@Test
    public void createNewXml() throws Exception{
		Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "hncu" );
        root.addElement("department").addAttribute("id", "hnuc001").addElement("xky").setText("信息科学与工程学院");
        
        //保存
        XMLWriter w = new XMLWriter(new FileOutputStream("./xml5/hncu.xml"));
        w.write(document);
	}
	
	//xpath用法
	@Test
    public void xpathDemo() throws Exception{
		SAXReader sax = new SAXReader();
		Document dom = sax.read("./xml5/contact.xml");
		//String xpath="/*/name";//第一个"/"表示当前元素
		//String xpath="//contact/name";//选择contact下面的name(儿子)
		//String xpath="//aaa/preceding::*";//选择<aaa>前面的所有元素
		String xpath="//*[@id]";//选择具有id属性的所有元素
		Element root = dom.getRootElement();
		System.out.println(root.getName());
		List<Element> list = root.selectNodes(xpath);
		for(Element e:list){
			System.out.println(e.getName()+"---"+e.getText());
		}
	}
	
	//xpath用法
	@Test
	public void xpathDemo2() throws Exception{
		SAXReader sax = new SAXReader();
		Document dom = sax.read("./xml5/contact.xml");
		Scanner sc = new Scanner(System.in);
		String name = sc.nextLine();
		name = name.toLowerCase();
		String pwd = sc.nextLine();
		pwd = pwd.toLowerCase();
		
		//String xpath="//user[@name][@pwd]";//选择同时包含name和pwd属性的user元素
		//String xpath="//user[@name='Jack'][@pwd='1234']";//选择name='Jack'且pwd='1234'那个user元素
		//String xpath="//user[@name='"+name+"'][@pwd='"+pwd+"']";//选择name='Jack'且pwd='1234'那个user元素
		String xpath="//user[fn:lower-case(@name)='"+name+"'][fn:lower-case(@pwd)='"+pwd+"']";//选择name='Jack'且pwd='1234'那个user元素
		List<Element> list = dom.selectNodes(xpath);
		System.out.println(list.size());
//		for(Element e:list){
//			System.out.println(e.getName());
//			List<Element> eList = e.selectNodes("//contact/name");
//			for(Element e2:eList){
//				System.out.println(e2.getText());
//			}
//		}
	}
	
}
contact.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<contacts>
  <user name="Jack" pwd="1234">
    <contact id="a001">
       <name>Tom</name>
       <sex>Male</sex>
       <tel>13812345678</tel>
    </contact>
    <contact id="a002">
       <name>Rose</name>
       <sex>Female</sex>
       <tel>13887654321</tel>
       <pub>
          <aaa>
            <name>hncu...</name>
          </aaa>
       </pub>
    </contact>
	  <contact id="2fe4c73b7cc743b0a34bcab6184c1031">
		  <name>Mike</name>
		  <tel>12345678900</tel>
		  <sex>aa</sex>
	  </contact>
  </user>
 
  <user name="Tom" pwd="4321">
    <contact id="b001">
       <name>Jack</name>
       <sex>Male</sex>
       <tel>13800000000</tel>
    </contact>
    <contact id="b002">
       <name>Rose</name>
       <sex>Female</sex>
       <tel>13887654321</tel>
    </contact>
  </user>
  
  <name>abc...</name>
</contacts>
users.xml

<?xml version="1.0" encoding="UTF-8"?>
<users> 
  <user id="A001"> 
    <name>Jack</name>  
    <age>25</age> 
  </user>  
  <user id="A002"> 
    <name>张三</name>  
    <age>80</age> 
  </user>  
  <user id="C001">
    <name>李四</name>
    <age>32</age>
  </user>
  <user id="C003">
    <name>玛丽</name>
    <age>24</age>
  </user>  
</users>