2010-04-02 8 views
33

Ho continuato a giocherellare per oltre venti minuti e il mio Google-foo mi ha deluso.Documento XML a stringa?

Diciamo che ho un documento XML creato 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? 

Come faccio a convertire l'oggetto documento in una stringa di testo?

+2

sei legato in ad usare 'org.w3c.dom'? Altre API DOM (Dom4j, JDOM, XOM), rendono questo genere di cose molto più facile. – skaffman

risposta

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

È possibile utilizzare questo pezzo di codice per realizzare ciò che si vuole:

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