2010-04-02 18 views
33

He estado jugando con esto durante más de veinte minutos y mi Google Foo me está fallando.XML Document to String?

Digamos que tengo un documento XML creado en 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? 

¿Cómo convierto el objeto de documento en una cadena de texto?

+2

¿Está ligado a que el uso de 'org.w3c.dom'? Otras API DOM (Dom4j, JDOM, XOM) hacen que este tipo de cosas sea muchísimo más fácil. – skaffman

Respuesta

86
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); 
    } 
} 
8

Puede utilizar esta pieza de código para lograr lo que quiere:

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(); 
}