Create an XML document and save it to a disk file (GBK)

Source: Internet
Author: User
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!");
 }
		
	}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.