小编典典

XML文档转换成字符串?

java

我已经摆弄了二十多分钟,而我的Google-foo让我失望了。

假设我有一个用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?

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


阅读 228

收藏
2020-09-11

共1个答案

小编典典

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);
    }
}
2020-09-11