Dom4j

Dom4j开源库,用于解析XML,应用于java平台(jdk必须8以上版本)

下载地址:https://mvnrepository.com/artifact/org.dom4j/dom4j

引用:右键lib的Dom4j文件构建路径

Dom4j_第1张图片

使用Dom4J读取XML文件

package com.ulikeme.dom4j;

import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
 * 使用Dom4J读取XML文件
 * @author QD
 *
 */
public class HrReader {
	public void readXml() {
		String file="E:/hr.xml";
		//SAXReader类是读取xml的核心类,用于将XML解析后以树的形式保存在内存中
		SAXReader reader=new SAXReader();
		try {
			Document document=reader.read(file);
			//获取XML文档根节点,即hr标签
			Element root= document.getRootElement();
			//elements用于获取指定的标签集合
			List employees=root.elements("employee");
			for(Element employee:employees) {
				//element方法用于获取唯一的子节点对象
				Element name=employee.element("name");
				String empName=name.getText(); //getText()获取标签文本值
				System.out.println(empName);
				
				System.out.println(employee.elementText("age"));
				System.out.println(employee.elementText("salery"));
				
				Element department=employee.element("department");
				System.out.println(department.element("dname").getText());
				System.out.println(department.element("address").getText());
				
				//获取属性
				Attribute att=employee.attribute("no");
				System.out.println(att.getText());
				System.out.println("-----------------------------------");
			}
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	//主方法
	public static void main(String[] args) {
		HrReader reader=new HrReader();
		reader.readXml();
	}
	
}

 

向XML文件中追加数据(添加员工)

package com.ulikeme.dom4j;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

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

/**
 * 向XML文件中追加数据(添加员工)
 * @author QD
 *
 */
public class HrWrite {
	
	public void writeXml() {
		String file="E:/hr.xml";
		SAXReader reader=new SAXReader();
		try {
			Document document=reader.read(file);
			Element root= document.getRootElement();
			Element employee=root.addElement("employee");
			employee.addAttribute("no", "3311");
			Element name=employee.addElement("name");
			name.setText("王维");
			
			employee.addElement("age").setText("33");
			employee.addElement("salery").setText("3600");
			Element department= employee.addElement("department");
			department.addElement("dname").setText("人事部");
			department.addElement("address").setText("深圳");
			
			//从内存写入文件
			Writer writer=new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); //utf-8防止中文乱码
			document.write(writer);
			writer.close();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		HrWrite newXml=new HrWrite();
		newXml.writeXml();
	}

}

 

你可能感兴趣的:(java学习,Dom4j,xml,java)