方法链的编程风格(method chain style)
Element e = new Element ("test");
e.setAttribute("aa","bb");
e.setAttribute("cc","a");
e.setAttribute("aa","bb").setAttribute("cc","a");
对于JDOM的Format类的getRawFormat方法,通常用于XML数据网络传送,因为这
种格式会去掉所有不必要的空白,因此能减少网络传送的数据量。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.*;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class JdomTest1
{
public static void main(String[] args) throws FileNotFoundException,
IOException
{
Document document = new Document();
Element root = new Element("root");
document.addContent(root);
Comment comment= new Comment("This is a comment");
root.addContent(comment);
Element e = new Element("hello");
e.setAttribute("sohu","www.suhu.com");
root.addContent(e);
Element e2 = new Element("world");
Attribute attr = new Attribute("test","hehhe");
e2.setAttribute(attr);
e.addContent(e2);
e2.addContent(new Element("aaa").setAttribute
("a","b").setAttribute("x","y").setAttribute("gg","hh").setText("text
content"));
Format format = Format.getPrettyFormat();
format.setIndent(" ");
format.setEncoding("UTF-8");
XMLOutputter out = new XMLOutputter(format);
out.output(document,new FileOutputStream("jdom.xml"));
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class JdomTest2
{
public static void main(String[] args) throws IOException,
IOException, JDOMException
{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("jdom.xml"));
Element element = doc.getRootElement();
System.out.println(element.getName());
Element hello=element.getChild("hello");
System.out.println(hello.getText());
List list=hello.getAttributes();
for(int i=0;i<list.size();i++)
{
Attribute attr = (Attribute)list.get(i);
String attrName = attr.getName();
String attrValue = attr.getValue();
System.out.println(attrName+"="+attrValue);
}
//hello.removeChild("world");
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat
().setIndent(" "));
out.output(doc,new FileOutputStream("jdom2.xml"));
}
}