如何使用DOM4J对XML文件进行解析?

a.xml

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

<班级> 
  <学生> 
    <名字 外号="黑旋风">李逵</名字>  
    <年龄>100</年龄>  
    <性别>男</性别> 
  </学生>  
  <学生> 
    <名字 外号="黑旋风">宋江</名字>  
    <年龄>34</年龄>  
    <性别>男</性别> 
  </学生>  
  <学生> 
    <名字 外号="黑旋风">武松</名字>  
    <年龄>43</年龄>  
    <性别>男</性别> 
  </学生>  
  <学生> 
    <名字 外号="黑旋风">林冲</名字>  
    <年龄>45</年龄>  
    <性别>男</性别> 
  </学生> 
</班级>
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;

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;

/*1.为什么会有dom4j
 * dom: 比较消耗内存
 * dom4j:可以提高效率,
 * 必须要导入jar包
 * 
 * */
public class Dom4jTest {
	
	public static void main(String[] args) throws Exception {
		  //1.得到解析器
		SAXReader reader = new SAXReader();
		//2.指定解析哪个xml文件
		Document document = reader.read(new File("a.xml"));
		list(document.getRootElement());//遍历;查全部文档信息
		//read(document);//查部分元素的信息
		//add(document);
		//del(document);
		//update(document);
	}
	
	//修改(修改年龄)
	public static void update(Document doc) throws Exception{
		    //得到所有学生元素的年龄
	 List<Element> sts= doc.getRootElement().elements("学生");
	 
	 //遍历
	   for(Element el:sts){
		   //从el里面取出年龄  修改年龄元素里面文本的值
		   Element age=el.element("年龄");// 获得 el 的下一级元素  年龄
		   
		  // int a=
		   //age.setText(a+"");
		   age.setText((Integer.parseInt(age.getText())+12)+"");
		   
		   //修改属性的值  用到的方法
		   Element name=el.element("名字");
		   //如果说属性名存在 ,就是更新     不存在就是添加
		   name.addAttribute("外号", "黑旋风");
		   
		 //直接输出会出现中文乱码的现象(dom4j给我们提供了一个类OutputFormat)
		    OutputFormat output = OutputFormat.createPrettyPrint();
		    //指定的输出格式是什么:  utf-8
		       output.setEncoding("utf-8");
		    
		    //把我们的xml文件更新(给我们提供了一个类XMLWriter)
		    XMLWriter writer = new XMLWriter(new FileOutputStream(new
		    		File("a.xml")),output);
		    //把文件写到指定的文档里doc  write(doc)
		    writer.write(doc);
		    writer.close();
		   
	   }
	}
	
	
	
	//删除(删除第一个学生)
	public static void del(Document doc) throws Exception{
		//1.找到该学生
		Element stu=doc.getRootElement().element("学生");
		//2.删除学生 (首先找到他的父亲,然后通过父亲来删除它)  getParent().remove(stu)
		//stu.getParent().remove(stu);
		
		//删除元素的某个属性
		//Attribut a=stu.attribute("外号")
		//stu.remove(a);
		stu.remove(stu.attribute("外号"));
		
		 //直接输出会出现中文乱码的现象(dom4j给我们提供了一个类OutputFormat)
	    OutputFormat output = OutputFormat.createPrettyPrint();
	    //指定的输出格式是什么:  utf-8
	       output.setEncoding("utf-8");
	    
	    //把我们的xml文件更新(给我们提供了一个类XMLWriter)
	    XMLWriter writer = new XMLWriter(new FileOutputStream(new
	    		File("a.xml")),output);
	    //把文件写到指定的文档里doc  write(doc)
	    writer.write(doc);
	    writer.close();
	}
	
	
	//添加元素(学生元素)
	public static void add(Document doc) throws Exception{
			//首先我们要创建一个元素,怎样建立一个元素,我们要用到dom4j给我们提供的类
		    Element newStu=DocumentHelper.createElement("学生");
		    Element newStu_name=DocumentHelper.createElement("名字");
		            
		   //给元素添加属性
		    newStu_name.addAttribute("外号", "123");
		    //添加文本
		    newStu_name.setText("武松");
		    
		    //把子元素(节点)添加到newStu  方法:
		    newStu.add(newStu_name);
		    //再把newStu加到根元素里
		    doc.getRootElement().add(newStu);
		    
		    //直接输出会出现中文乱码的现象(dom4j给我们提供了一个类OutputFormat)
		    OutputFormat output = OutputFormat.createPrettyPrint();
		    //指定的输出格式是什么:  utf-8
		       output.setEncoding("utf-8");
		    
		    //把我们的xml文件更新(给我们提供了一个类XMLWriter)
		    XMLWriter writer = new XMLWriter(new FileOutputStream(new
		    		File("/a.xml")),output);
		    //把文件写到指定的文档里doc  write(doc)
		    writer.write(doc);
		    writer.close();
		    
	}
	
	
	//如何指定读取某个元素(要求:读取第一个学生的信息)
	public static void read(Document doc){
		//1.得到根元素
		Element root=doc.getRootElement();
		//
		//root.elements() 表示的就是root下所有的学生元素  .get(index i) 指定索引位置的元素
		//root.element("下的某个元素") 表示的就是root下的某个元素
		Element stu=(Element)root.elements("学生").get(0);
		//找到学生元素下面的 名字元素
		    Element stu_name=stu.element("名字");
		    //stu_name.attributeValue("外号")  操作属性   获取属性值
		    System.out.println(stu_name.attributeValue("外号"));
		    //getText():获取文本值
		    System.out.println(stu_name.getText());
	}
	
	
	
	
	
	//遍历xml文件  迭代递归方法 输出xml文件
	public static void list(Element ele){
		System.out.println(ele.getName()+ele.getTextTrim());
		//获取子元素  elementIterator();
		Iterator ite=ele.elementIterator();
		//循环输出
		while(ite.hasNext()){
			Element e=(Element)ite.next();
			//递归的形式
			list(e);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/Java_stud/article/details/82350262