首页 > 代码库 > DOM4J读取XML

DOM4J读取XML

  实现读取XML元素和添加元素

package cn.test;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import org.junit.Test;/** * 需要两个jar包 * dom4j-1.6.1.jar-306 KB * jaxen-1.1-beta-6.jar * @author zy * */public class Dom4jTest {		@Test	public void readXML(){		String path = "D:/Temp/users.xml";		//创建解析器		SAXReader reader = new SAXReader();		try {			//得到document			Document doc = reader.read(path);			//通过xpath查询得到Element			Element ele = (Element) doc.selectSingleNode(					"//user[@username=‘scott‘]");			//获取该元素的名为username的属性值			String username = ele.attributeValue("username");			String password = ele.attributeValue("password");			System.out.println(username+","+password);		} catch (DocumentException e) {			e.printStackTrace();		}	}		@Test	public void writeXML(){		String path = "D:/Temp/users.xml";		//创建解析器				SAXReader reader = new SAXReader();				try {					//得到document					Document doc = reader.read(path);					//得到根元素					Element root = doc.getRootElement();					//通过根元素创建新元素user					Element userEle = root.addElement("user");					//为userEle设置属性					userEle.addAttribute("username","scott");					userEle.addAttribute("password","tiger");					//设置文档格式,使用\t缩进,使用换行					OutputFormat format = new OutputFormat("\t",true);					//删除原来已有的文档的缩进和换行					format.setTrimText(true);					//创建XMLWriter					XMLWriter writer;					try {						 writer = new XMLWriter(						  new OutputStreamWriter(								  new FileOutputStream(path),"utf-8"),format);					//保存document对象						writer.write(doc);						writer.close();					} catch (Exception e) {						e.printStackTrace();					} 				} catch (DocumentException e) {					e.printStackTrace();				}	}}

  

xml

<?xml version="1.0" encoding="UTF-8"?><users>	<user username="scott" password="tiger"/></users>

  

DOM4J读取XML