Package com.bjpowernodetest;
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;
Import Junit.framework.TestCase; /** * * @author Kevin * Create an XML document and save it to a disk file (GBK) */public class Testxmlwriter extends TestCase {/** <?xml versio N= "1.0" encoding= "UTF-8"?> <items> <item> <id>10003</id> <name> Baoding < /name> </item> <item> <id>10004</id> <name> Tianjin </name> </ite M> </items> * * */** * Create the above XML */public void Testxmlwriter () {//Create an XML document tree
Documenthelper.createdocument ();
Create root node items Element itemselement = document.addelement ("items");
Create the item sub-node under the root node Element itemelement = Itemselement.addelement ("item"); Item node has two child nodes Element idelement = Itemelement.addelemENT ("id");
Idelement.settext ("10003");
Element nameelement = itemelement.addelement ("name");
Nameelement.settext ("Baoding");
Format XML document, nice format OutputFormat OutputFormat = Outputformat.createprettyprint ();
Sets the XML encoding method, which is to save the XML document to the file with the specified encoding, and let the browser parse the XML document Outputformat.setencoding ("GBK") with the specified encoding method; try {//XMLWriter a file (test.xml) corresponding to the disk, here (GBK encoding) to use FileWriter, otherwise it may lead to garbled, such as with FileOutputStream, will cause garbled XMLWriter XMLWriter =
New XMLWriter (New FileWriter ("C:/test.xml"), OutputFormat);
Writes the created XML document to the file Xmlwriter.write (documents);
Xmlwriter.close ();
System.out.println ("Write XML document to file successfully!");
} catch (IOException e) {e.printstacktrace ();
throw new RuntimeException ("Failed to write XML document to file!");
}
}
}