JDom解析xml

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"));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值