2010-04-02 10 views
33

Mylę się z tym od ponad dwudziestu minut, a mój Google-foo mnie zawodzi.Dokument XML na ciąg?

powiedzmy Mam dokumentu XML utworzonego w 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? 

Jak przekonwertować obiekt dokumentu w ciągu tekstowym?

+2

Czy jesteś przywiązany do użyciem 'org.w3c.dom'? Inne API DOM (Dom4j, JDOM, XOM) sprawiają, że tego typu rzeczy są o wiele łatwiejsze. – skaffman

Odpowiedz

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

Można użyć tego fragmentu kodu, aby osiągnąć to, co chcesz:

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(); 
} 
Powiązane problemy