首先下载jdom的压缩文件:http://www.jdom.org/dist/binary/,解压后在build文件下找到jdom.jar添加到你的工程里。
//添加根节点animal
Element root = new Element("animal");
Document myDocument = new Document(root);
//为根节点添加子节点dog
Element dog = new Element("dog");
root.addContent(dog);
//为dog节点添加相应的属性节点
dog.addContent(new Element("name").addContent("小次郎"));
dog.addContent(new Element("sex").addContent("male"));
dog.addContent(new Element("age").addContent("3"));
dog.addContent(new Element("color").addContent("黑白"));
//设置输出的格式及编码
org.jdom.output.Format format = org.jdom.output.Format.getCompactFormat();
format.setEncoding("UTF-8");
format.setIndent(" "); //缩进2个空格后换行,空格数自己设
//输出xml
try {
XMLOutputter outputter = new XMLOutputter(format);
outputter.output(myDocument, new FileOutputStream("d:\\1.xml"));
} catch (Exception e) {
e.printStackTrace();
}
//生成的xml文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<animal>
<dog>
<name>小次郎</name>
<sex>male</sex>
<age>3</age>
<color>黑白</color>
</dog>
</animal>
下载源代码