DOM4J读取XML
Posted 头痛不头痛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章