Java generates XML files

Source: Internet
Author: User

The import org.w3c.dom.Document is also used here;

You first create a Document object, assign a value to the object, and then convert the document object using Transformer's transformer conversion method to a file or other type for the desired operation.

1. Create a Documentbuilder object

Documentbuilderfactory documentbuilderfactory=documentbuilderfactory.newinstance ();            Documentbuilder    = documentbuilderfactory.newdocumentbuilder ();

2. Create Document object and assign value

Documentbuilder's api:http://download.oracle.com/technetwork/java/javase/6/docs/zh/api/javax/xml/parsers/ Documentbuilder.html#parse%28java.lang.string%29

Document Document=documentbuilder.parse (URI);//I'm using the parse method to parse the file contents of the URI address and convert the content to a string

Create a document empty object and assign an example of the value:

3. Convert document into XML file

/* Generate transformer objects */
Transformerfactory factory=transformerfactory.newinstance (); Transformer Transformer=factory.newtransformer ();
StringWriter writer=new StringWriter (); /* Character output stream */
Transformer.transformer (new Domsource (document), new Streamresult (writer));//Convert the value in document to the output stream
System.out.println (Writer.tostring ());
File Xmlfile=new file ("Newxml.xml");
Transformer.transformer (new Domsource (document), New Streamresult (xmlfile));//writes the value in document to the file, automatically completes the entity of the file

Java generates XML files

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.