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