【问题标题】:XML Document to String?XML文档到字符串?
【发布时间】:2011-02-03 18:37:09
【问题描述】:

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

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

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

【问题讨论】:

  • 您是否习惯使用org.w3c.dom?其他 DOM API(Dom4j、JDOM、XOM)让这类事情变得非常容易。

标签: java


【解决方案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);
    }
}

【讨论】:

    【解决方案2】:

    你可以使用这段代码来完成你想要的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-24
      • 2022-01-15
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多