JDom解析xml要比JDK解析好用很多,所以基本上项目上开发我都用这个,做个记录吧。废话不多说,直接上代码:
首先示例的xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="person1" username="zhengmin" password="123">
</person>
<person id="person2" username="yaoying" password="456" />
<person id="person3" username="zhengkai" password="333" />
</persons>
用JDom解析要先在工程中加入JDom的jar包,然后读写功能如下:
package jdom.demo;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;
public class XmlParse {
/**
* 解析po.xml
* @throws JDOMException
* @throws IOException
*/
public static void xmlParse() throws JDOMException, IOException
{
SAXBuilder builder = new SAXBuilder();
InputStream file = new FileInputStream("src/main/java/xml/po.xml");
Document document = builder.build(file);
Element root = document.getRootElement();
List<Element> children = root.getChildren();
for (Element e : children)
{
System.out.println("ID:" + e.getAttributeValue("id"));
System.out.println("username : " + e.getAttributeValue("username"));
System.out.println("password: " + e.getAttributeValue("password"));
}
}
/**
* 往po.xml后追加一个person节点
* @throws JDOMException
* @throws IOException
*/
public static void addXml() throws JDOMException, IOException
{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build("src/main/java/xml/po.xml");
Element root = doc.getRootElement();
Element new1 = new Element("person");
new1.setAttribute("id", "person4");
new1.setAttribute("username", "zzzzz");
new1.setAttribute("password", "333");
root.addContent(new1);
XMLOutputter out = new XMLOutputter();
out.output(doc, new FileOutputStream("po.xml"));
}
}