Writing Only the Text of a DOM Document : XML Serialization « XML « Java Tutorial






import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    Transformer xformer = TransformerFactory.newInstance().newTransformer();

    xformer.setOutputProperty(OutputKeys.METHOD, "text");

    Source source = new DOMSource(doc);
    Result result = new StreamResult(new File("outfilename.xml"));
    xformer.transform(source, result);
  }
}








33.21.XML Serialization
33.21.1.Saving a DOM tree to XML file javax.xml.parsers (JAXP)
33.21.2.PropsToXML takes a standard Java properties file, and converts it into an XML file
33.21.3.Writing a DOM Document to an XML File
33.21.4.Writing Only the Text of a DOM Document
33.21.5.Create an XML document with DOM
33.21.6.Strip extra spaces in a XML string
33.21.7.Extracting an XML formatted string out of a DOM object