Mar 10

A Transformer can be used to write the XML for a DOM Document to a String. As the name implies a Transformer transforms a Source object into a Result, in this case the Source is the DOM Document, and the Result is a StringWriter (which the resulting XML String can be extracted from).

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);
Source source = new DOMSource(document);
transformer.transform(source, result);
writer.close();
String xml = writer.toString();

written by objects \\ tags: , , ,


One Response to “How to create XML String from a DOM Document?”

  1. AppeloAppelo Says:

    isolating HTML tags

    In Javascript for Selenium Reading XML from DOM when XML file is displayed in Browser:

    function loadXMLFromDOM2XMLString( xmlString, xmltag, currentChildNode ) {

    var nodes = currentChildNode.childNodes;
    var i = 0 ;
    var node = nodes[i];
    var slash = ‘/’;
    var lessthan = ‘<’;
    var greaterthan = ‘>’;
    while ( i < nodes.length) {
    if (node.data == null) {xmltag = lessthan+node.localName+greaterthan;} else {xmltag = node.data;};
    xmlString = xmlString + xmltag;
    xmlString = loadXMLFromDOM2XMLString( xmlString, xmltag, node );
    if (node.data == null) {xmltag = lessthan+slash+node.localName+greaterthan;} else {xmltag = "";};
    xmlString = xmlString + xmltag;
    i++;
    node = nodes[i];
    }
    return xmlString ;
    } ;
    var xmlString = "";
    var xmltag = "";

    var currentChildNode = window.document;

    xmlString = loadXMLFromDOM2XMLString( xmlString, xmltag, currentChildNode );
    xmlString;

Leave a Reply

You must be logged in to post a comment.