import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/*
* 用JDOM写XML文档
*/
public class JDOM {
public static void main(String[] args) throws FileNotFoundException, IOException {
//构建一个文档
Document document = new Document();
//构建一个元素
Element root = new Element("root");
//把root加成根元素
document.addContent(root);
//构建一个注释
Comment comment = new Comment("this is a comment");
//把注释加到根元素上
root.addContent(comment);
//构建一个元素叫hello
Element e = new Element("hello");
//设置元素的属性sou为www.souhu.com
e.setAttribute("sou","www.souhu.com");
//把元素e加在root上
root.addContent(e);
//构建e2为world
Element e2 = new Element("world");
//设置属性为google的值为www.googel
e2.setAttribute("google","www.google");
//把e2加在了root上
root.addContent(e2);
//建立一个e3元素
Element e3 = new Element("Hello");
//构建一个属性名为text值为haha
Attribute attr = new Attribute("text","haha");
//把属性加在e3上
e3.setAttribute(attr);
//把e3加在root上
root.addContent(e3);
//设置文档的显示格式
Format format = Format.getPrettyFormat();
//缩进四个空格
format.setIndent(" ");
//设置输出流
XMLOutputter out = new XMLOutputter(format);
//把文档和文件用流关联起来
out.output(document, new FileOutputStream("text.xml"));
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/*
* 用JDOM写XML文档
*/
public class JDOM {
public static void main(String[] args) throws FileNotFoundException, IOException {
//构建一个文档
Document document = new Document();
//构建一个元素
Element root = new Element("root");
//把root加成根元素
document.addContent(root);
//构建一个注释
Comment comment = new Comment("this is a comment");
//把注释加到根元素上
root.addContent(comment);
//构建一个元素叫hello
Element e = new Element("hello");
//设置元素的属性sou为www.souhu.com
e.setAttribute("sou","www.souhu.com");
//把元素e加在root上
root.addContent(e);
//构建e2为world
Element e2 = new Element("world");
//设置属性为google的值为www.googel
e2.setAttribute("google","www.google");
//把e2加在了root上
root.addContent(e2);
//建立一个e3元素
Element e3 = new Element("Hello");
//构建一个属性名为text值为haha
Attribute attr = new Attribute("text","haha");
//把属性加在e3上
e3.setAttribute(attr);
//把e3加在root上
root.addContent(e3);
//设置文档的显示格式
Format format = Format.getPrettyFormat();
//缩进四个空格
format.setIndent(" ");
//设置输出流
XMLOutputter out = new XMLOutputter(format);
//把文档和文件用流关联起来
out.output(document, new FileOutputStream("text.xml"));
}
}
下面是生成的文件
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!--this is a comment-->
<hello sou="www.souhu.com" />
<world google="www.google" />
<Hello text="haha" />
</root>