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

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?

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);

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();
}

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);

Need Your Help

EditText and MultiAutoCompleteTextView suggestions

android autocomplete android-edittext

I'm using a MultiAutoCompleteTextView in my app to show various suggestions.

Class auto-wiring in Objective C

objective-c ios xcode design-patterns inversion-of-control

From past thread: Dependency injection framework for Cocoa?, although it was said that IoC framework is not needed to dynamic language such as Obj-C, but people often missed one of the core feature -

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.