2010-04-02 159 views
33

我一直在擺弄這個問題超過20分鐘,而我的Google-foo讓我失望。將XML文檔轉換爲字符串?

比方說,我在爪哇(org.w3c.dom.Document中)創建的XML文檔:

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? 

如何轉換的文檔對象轉換爲文本字符串?

+2

你綁成使用'org.w3c.dom'?其他DOM API(Dom4j,JDOM,XOM)使這種事情變得非常簡單。 – skaffman 2010-04-02 15:26:22

回答

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

您可以使用這段代碼來完成你想要什麼:

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