XML Document to String?
Asked Answered
K

2

59

I've been fiddling with this for over twenty minutes and my Google-foo is failing me.

Let's say I have an XML Document created in Java (org.w3c.dom.Document):

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();

Element rootElement = document.createElement("RootElement");
Element childElement = document.createElement("ChildElement");
childElement.appendChild(document.createTextNode("Child Text"));
rootElement.appendChild(childElement);

document.appendChild(rootElement);

String documentConvertedToString = "?" // <---- How?

How do I convert the document object into a text string?

Koniology answered 2/4, 2010 at 15:17 Comment(1)
Are you tied into to using org.w3c.dom? Other DOM APIs (Dom4j, JDOM, XOM), make this sort of thing an awful lot easier.Alto
D
143
public static String toString(Document doc) {
    try {
        StringWriter sw = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Error converting to String", ex);
    }
}
Deboradeborah answered 2/4, 2010 at 15:21 Comment(0)
H
17

You can use this piece of code to accomplish what you want to:

public static String getStringFromDocument(Document doc) throws TransformerException {
    DOMSource domSource = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
    return writer.toString();
}
Hopehopeful answered 2/4, 2010 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.