48

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?

Roman
  • 64,384
  • 92
  • 238
  • 332

3 Answers3

76

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);
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • This will save to xml file in build project folder. But if I want to save it in the original xml file, then how should I do that? I try pasting original xml file Path but it still doesn't work. –  Nov 01 '20 at 03:35
2

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();
}
M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
0

That will give you possibility to define xml format

new XMLWriter(new FileOutputStream(fileName),
              new OutputFormat(){{
                        setEncoding("UTF-8");
                        setIndent("    ");
                        setTrimText(false);
                        setNewlines(true);
                        setPadText(true);
              }}).write(document);
M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
Frank M.
  • 997
  • 1
  • 10
  • 19