Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save parsed and changed DOM document in xml file?

Tags:

java

dom

xml

I have xml-file. I need to read it, make some changes and write new changed version to some new destination.

I managed to read, parse and patch this file (with DocumentBuilderFactory, DocumentBuilder, Document and so on).

But I cannot find a way how to save that file. Is there a way to get it's plain text view (as String) or any better way?

like image 365
Roman Avatar asked Dec 30 '10 10:12

Roman


People also ask

How DOM parses the XML file?

DOM parser parses the entire XML file and creates a DOM object in the memory. It models an XML file in a tree structure for easy traversal and manipulation. In DOM everything in an XML file is a node. The node represents a component of an XML file.

Can we create an XML Document using DOM parser?

In short the basic steps one has to take in order to create an XML File withe a DOM Parser are: Create a DocumentBuilder instance. Create a Document from the above DocumentBuilder . Create the elements you want using the Element class and its appendChild method.

What is DOM parser in XML?

Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it. This parser uses an object-based approach for creating and parsing the XML files. In General, a DOM parser loads the XML file into the Android memory to parse the XML document.


2 Answers

Something like this works:

Transformer transformer = TransformerFactory.newInstance().newTransformer(); Result output = new StreamResult(new File("output.xml")); Source input = new DOMSource(myDocument);  transformer.transform(input, output); 
like image 118
skaffman Avatar answered Sep 20 '22 20:09

skaffman


That will work, provided you're using xerces-j:

public void serialise(org.w3c.dom.Document document) {   java.io.ByteArrayOutputStream data = new java.io.ByteArrayOutputStream();   java.io.PrintStream ps = new java.io.PrintStream(data);    org.apache.xml.serialize.OutputFormat of =                       new org.apache.xml.serialize.OutputFormat("XML", "ISO-8859-1", true);   of.setIndent(1);   of.setIndenting(true);   org.apache.xml.serialize.XMLSerializer serializer =                       new org.apache.xml.serialize.XMLSerializer(ps, of);   // As a DOM Serializer   serializer.asDOMSerializer();   serializer.serialize(document);    return data.toString(); } 
like image 32
Lukas Eder Avatar answered Sep 23 '22 20:09

Lukas Eder