package com.liuc.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class XMLInsert {
/**
* @param args
*/
public static void main(String[] args) {
insert(new File("person.xml"));
}
private static void insert(File file) {
try {
SAXBuilder sax=new SAXBuilder();
Document doc=sax.build("person.xml");
if (doc!=null) {
if (doc.hasRootElement()) {
Element root=doc.getRootElement();
Element person=new Element("person");
root.addContent(person);
Attribute attr=new Attribute("perid", "1003");//创建属性
person.setAttribute(attr);//添加属性
Element name=new Element("name");
name.setText("wangwu");
person.addContent(name);
Element age=new Element("age");
age.setText("25");
person.addContent(age);
Element address=new Element("address");
address.setText("saoziying");
person.addContent(address);
Element sex=new Element("sex");
sex.setText("男");
person.addContent(sex);
XMLOutputter outp=new XMLOutputter();//用于输出JDOM文档
Format format=Format.getPrettyFormat();//格式化文档
format.setEncoding("UTF-8");
outp.setFormat(format);
FileOutputStream fos=new FileOutputStream("person.xml");
outp.output(doc, fos);
}
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
XML文件
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person perid="1001">
<name>zhangsan</name>
<age>89</age>
<address>安徽淮北</address>
<sex>男</sex>
</person>
<person perid="1002">
<name>lisi</name>
<age>56</age>
<address>北京海淀</address>
<sex>女</sex>
</person>
</persons>