public class JDomWriter {
public static void main(String[] args) {
Document doc = new Document();
Element root = new Element("root");
doc.addContent(root); //添加根元素
Comment comment = new Comment("这是我的注释");
root.addContent(comment); //添加注释
// Element student1 = new Element("student");
// root.addContent(student1);
// student1.setAttribute("id", "1000"); //给student元素添加一个属性
Element student1 = new Element("student").setAttribute("id", "11104053"); //使用方法链的方法添加属性
root.addContent(student1);
Element username = new Element("username").setText("张三");
student1.addContent(username);
// Element student2 = new Element("student");
// root.addContent(student2);
// Attribute attribute = new Attribute("id", "1001");
// student2.setAttribute(attribute); //添加属性的第二种方式
//格式化输出
Format format = Format.getPrettyFormat();
// format.setEncoding("utf-8"); //默认就是utf-8
format.setIndent(" "); //四个空格
XMLOutputter out = new XMLOutputter(format);
try {
// out.output(doc, new FileOutputStream("jdom.xml")); //写到文件内
out.output(doc, System.out); //输出到控制台
} catch (Exception e) {
e.printStackTrace();
}
}
}