XML处理
利用dom4j处理xml的实例,这里演示生成xml的方法。待完善
import java.io.FileWriter;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class XMLGenerator {
private Document document;
public Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("author").addAttribute("name",
"James").addAttribute("location", "UK").addText(
"James Strachan");
Element author2 = root.addElement("author").addAttribute("name", "Bob")
.addAttribute("location", "US").addText("Bob McWhirter");
return document;
}
/*
* public void serializetoXML(Document document, OutputStream out, String
* aEncodingScheme) throws Exception { this.document = document;
* OutputFormat outformat = OutputFormat.createPrettyPrint();
* outformat.setEncoding(aEncodingScheme); XMLWriter writer = new
* XMLWriter(out, outformat); writer.write(this.document); writer.flush(); }
*/
public void write(Document document) throws IOException {
// 指定文件
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(document);
writer.close();
// 美化格式
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter(System.out, format);
writer.write(document);
// 缩减格式
format = OutputFormat.createCompactFormat();
writer = new XMLWriter(System.out, format);
writer.write(document);
}
public static void main(String[] args) {
XMLGenerator generator = new XMLGenerator();
try {
generator.write(generator.createDocument());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}