Java: write XML to file with transformer 

Joined:
03/21/2010
Posts:
49

April 07, 2011 21:30:54    Last update: April 07, 2011 21:30:54
This is the opposite of parsing. You can use javax.xml.transform.Transformer to output a DOM tree to a file.
import java.io.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class OutputXMLString {
    private static String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                                 + "<catalog>"
                                 + "<book id=\"1\">"
                                 + "<author>Charles Dickens</author>"
                                 + "<title>Oliver Twist</title>"
                                 + "</book>"
                                 + "</catalog>";

    public static void main(String[] args) throws Exception {
	DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
	DocumentBuilder b = f.newDocumentBuilder();
	Document doc = b.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));

	Element catalog = (Element) doc.getElementsByTagName("catalog").item(0);

	// add Mark Twain book
	Element tom = doc.createElement("book");
	catalog.appendChild(tom);

	Attr attr = doc.createAttribute("id");
	attr.setValue("2");
	tom.setAttributeNode(attr);

	// author
	Element author = doc.createElement("author");
	author.appendChild(doc.createTextNode("Mark Twain"));
	tom.appendChild(author);

	// title
	Element title = doc.createElement("title");
	title.appendChild(doc.createTextNode("The Adventures of Tom Sawyer"));
	tom.appendChild(title);
   
	// output XML with transformer
	TransformerFactory tf = TransformerFactory.newInstance();
	Transformer t = tf.newTransformer();
	DOMSource src = new DOMSource(doc);
	StreamResult res = new StreamResult(System.out);
	t.transform(src, res);
    }
}
Share |
| Comment  | Tags