any easy way to write out a XML DOM object to file?

K

Kaidi

Hello!

I am using Document and DOM to hold a XML file, and make some changes
to the Document. After that, I just wonder is there any easy way to
write the modified XML file back to disk? (loop all the nodes and
print them out is one way of course, any other better way?)

The piece of node is:

String filename="mytest.xml";
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse(new
File(filename));
// changes the doc, add, edit nodes, etc.

Now, I want to get the updated xml file from "doc", what to do?
Anything like doc.writeAsXMLFile("newFile.xml")?

Thanks and happy holiday. :)
 
A

Alex Kizub

Now, I want to get the updated xml file from "doc", what to do?
Anything like doc.writeAsXMLFile("newFile.xml")?

OutputFormat format = new OutputFormat(doc);
Writer writer = new FileWriter("newFile.xml");
XMLSerializer ser = new XMLSerializer(writer, format);
ser.serialize(doc);
writer.close();

Alex Kizub.
 
F

Ferenc Hechler

Hello,

XMLSerializer is deprecated (old xerces).
Some code I use to transform a Document into a String:

Document document = ...;
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
// serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
serializer.setOutputProperty(OutputKeys.INDENT,"yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
serializer.transform(domSource, streamResult);
String result = writer.getBuffer().toString();

Best regards,
feri
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top