package jdom;
import java.io.FileOutputStream;
import org.jdom2.Attribute;
import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
/**
* 文檔輸出實例
*
* @author user
*
*/
public class JDomTest1 {
public static void main(String[] args) throws Exception {
Document document = new Document();
Element root = new Element("root");
/* 將element指明爲根元素 */
document.addContent(root);
Comment comment = new Comment("This is my comments");
root.addContent(comment);
Element e = new Element("hello");
e.setAttribute("sohu", "www.sohu.com");
root.addContent(e);
Element e2 = new Element("world");
Attribute attr = new Attribute("test", "heh");
e2.setAttribute(attr);
e2.setText("neirong");
root.addContent(e2);
/* 輸出到文件中 */
Format format = Format.getPrettyFormat();
/* 設置每行的縮進 */
format.setIndent(" ");
XMLOutputter out = new XMLOutputter(format);
out.output(document, new FileOutputStream("jdom.xml"));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!--This is my comments-->
<hello sohu="www.sohu.com" />
<world test="heh">neirong</world>
</root>
********************************************
package jdom;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
/**
* 文檔輸入實例
*
* @author user
*
*/
public class JDomTest2 {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("jdom.xml"));
Element element = document.getRootElement();
System.out.println(element.getName());
Element hello = element.getChild("hello");
System.out.println(hello.getName());
Attribute attr = hello.getAttribute("sohu");
System.out.println(attr.getValue());
List<Attribute> attrList = hello.getAttributes();
for (Attribute attribute : attrList) {
System.out.println(attribute.getName() + " : "
+ attribute.getValue());
}
element.removeChild("world");
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent(
" "));
out.output(document, new FileOutputStream("jdom2.xml"));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!--This is my comments-->
<hello sohu="www.sohu.com" />
</root>