日期:2014-05-20 浏览次数:20880 次
package com.Gavin.tools.xml; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.XMLWriter; import java.io.*; /*<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE catalog SYSTEM "file://c:/Dtds/catalog.dtd"> <catalog> <!--An XML Catalog--> <?target instruction?> <journal title="XML Zone" publisher="IBM developerWorks"> <article level="Intermediate" date="December-2001"> <title>Java configuration with XML Schema</title> <author> <firstname>Marcello</firstname> <lastname>Vitaletti</lastname> </author> </article> </journal> ……//五本书 </catalog> */ public class XmlDom4J { public void generateDocument() { Document document = DocumentHelper.createDocument(); document.setXMLEncoding("GBK"); // System.out.println(document.getXMLEncoding()); Element root = document.addElement("catalog"); root.addComment("An XML Catalog"); root.addProcessingInstruction("target", "text"); /** * 为此 */ for(int i = 0; i < 5; i++) { Element journal = root.addElement("journal"); journal.addAttribute("title", "XML Zone"); journal.addAttribute("publisher", "IBM developerWorks"); Element article = journal.addElement("article"); article.addAttribute("level", "Intermediate"); article.addAttribute("date", "December-2001"); Element title = article.addElement("title"); title.setText("Java configuration with XML Schema"); Element author = article.addElement("author"); Element firstName = author.addElement("firstname"); firstName.setText("Marcello"); Element lastName = author.addElement("lastname"); lastName.setText("Vitaletti"); } document.addDocType("catalog", null, "file://c:/Dtds/catalog.dtd"); try { XMLWriter output = new XMLWriter(new FileWriter(new File("c:/catalog.xml"))); output.write(document); output.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } public static void main(String[] argv) { XmlDom4J dom4j = new XmlDom4J(); dom4j.generateDocument(); } }
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter output = new XMLWriter(new FileWriter(new File("c:/catalog.xml")),format);
output.write(document);