www.jdom.org----下載jar包並導入項目(導入源碼)
package com.java.xml;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
public class JDOM01 {
public static void main(String[] args) {
Element student=new Element("student");
Attribute id=new Attribute("id","001");
Attribute aa=new Attribute("aa","xx");
student.setAttribute(id);
student.setAttribute(aa);
Element name=new Element("name");
name.setText("張三");
student.addContent(name);
Element sex=new Element("sex");
sex.setText("男");
student.addContent(sex);
Element age=new Element("age");
sex.setText("20");
student.addContent(age);
Document document=new Document(student);
XMLOutputter out=new XMLOutputter();
out.setFormat(out.getFormat().setEncoding("UTF-8"));
try {
out.output(document, new FileOutputStream("src/student04.xml"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
結果:生成XML
<?xml version="1.0" encoding="UTF-8"?>
<student id="001" aa="xx"><name>張三</name><sex>20</sex><age /></student>