Originally posted by Ajith Kallambella:
[B]JAXP1.1 makes this a simple process. JAXP allows any XML Parser and any XML Transformer(such as an XSLT Engine) to be used using the JAXP API methods.
Each instance of the class javax.xml.transform.Transformer can be associated with an .xsl file, but it can have no association. javax.xml.transform.Source and javax.xml.transform.Result allow you to transform a Source object into the Result object. Both the Source and Result objects can be used to represent a org.w3c.dom.Node object (can be a Document), or a Stream type object (file, writer, stream).
By creating a Transform object without an underlying .xsl file, you can transform a Source(the internal DOM object) to a StreamResult(created from a file). This will write the DOM object to the file.
Transformer objects are created from the TransformerFactory object. The TransformerFactory object uses system properties to determine which parsers to use, allowing you to use this API with any JAXP parser. JAXP includes the Crimson parser and Xalan Transformer.
JAXP1.1 contains a few examples which help make the process easy to understand
Using last version of Xalan-Xerces all you have to do is to instanciate a new transformer (using the no parameter constructor) . That will instantiate a Transformer that transforms nothing, just copy source to destination.
You do not have to browse the whole DOM !
Using the Sun's Crimson you can cast the w3c document to type of XmlDocument and then use the write method.
This method works except for a small shortcoming - every save creates a carriage return character behind every closing tag. As I open modify and then save the same file these characters are adding up quickly.
Using Transformer Package that is included with JAXP1.1
This method works great except for one major flaw. If your document had a DOCTYPE, when you load your document, add some nodes etc.. and then save, you will notice the DOCTYPE declaration missing!!.
Hope that helps!