XML文档转换为字符串?

57

我已经折腾了二十多分钟,但我的谷歌搜索无法解决问题。

假设我有一个使用Java创建的XML文档(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?

如何将文档对象转换为文本字符串?


3
您是否必须使用 org.w3c.dom?其他 DOM API(Dom4j、JDOM、XOM)可以更轻松地完成这种工作。 - skaffman
2个回答

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

17
你可以使用这段代码来实现你想要的功能:
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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接