jdom 简单示例

package jdom;

import java.io.FileOutputStream;

import org.jdom2.Attribute;
import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
 * 文档输出实例
 * 
 * @author user
 * 
 */
public class JDomTest1 {

	public static void main(String[] args) throws Exception {
		Document document = new Document();
		Element root = new Element("root");
		/* 将element指明为根元素 */
		document.addContent(root);
		Comment comment = new Comment("This is my comments");
		root.addContent(comment);

		Element e = new Element("hello");
		e.setAttribute("sohu", "www.sohu.com");
		root.addContent(e);

		Element e2 = new Element("world");
		Attribute attr = new Attribute("test", "heh");
		e2.setAttribute(attr);
		e2.setText("neirong");
		root.addContent(e2);

		/* 输出到文件中 */
		Format format = Format.getPrettyFormat();
		/* 设置每行的缩进 */
		format.setIndent("	");
		XMLOutputter out = new XMLOutputter(format);
		out.output(document, new FileOutputStream("jdom.xml"));
	}
}
<?xml version="1.0" encoding="UTF-8"?>
<root>
	<!--This is my comments-->
	<hello sohu="www.sohu.com" />
	<world test="heh">neirong</world>
</root>

********************************************

package jdom;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
 * 文档输入实例
 * 
 * @author user
 * 
 */
public class JDomTest2 {

	public static void main(String[] args) throws Exception {
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File("jdom.xml"));
		Element element = document.getRootElement();
		System.out.println(element.getName());
		Element hello = element.getChild("hello");
		System.out.println(hello.getName());
		Attribute attr = hello.getAttribute("sohu");
		System.out.println(attr.getValue());
		List<Attribute> attrList = hello.getAttributes();
		for (Attribute attribute : attrList) {
			System.out.println(attribute.getName() + " : "
					+ attribute.getValue());
		}
		element.removeChild("world");
		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent(
				"	"));
		out.output(document, new FileOutputStream("jdom2.xml"));
	}
}

<?xml version="1.0" encoding="UTF-8"?>
<root>
	<!--This is my comments-->
	<hello sohu="www.sohu.com" />
</root>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值