【问题标题】:How to assign output of java document into string variable?如何将java文档的输出分配给字符串变量?
【发布时间】:2019-05-18 01:09:42
【问题描述】:

我有一个下面的代码,它是生成 XML 的最后一步。我想将输出 XML 存储到字符串变量中。如何在 Java 代码中做到这一点?目前,输出为文档格式。

public static void main(String[] args) {
    DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder icBuilder;
    try {
        icBuilder = icFactory.newDocumentBuilder();
        Document doc = icBuilder.newDocument();

        // Start of XML root element
        Element mainRootElement = doc
            .createElementNS("http://www.sampleWebSite.com/sampleWebSite/schema/external/message/actualDay/v1",
         "NS1:actualDayResponse");
        doc.appendChild(mainRootElement);
        Transformer transformer =
        TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);
        StreamResult console = new StreamResult(System.out);
        transformer.transform(source, console);
            System.out.println("\nXML DOM Created Successfully..");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

【问题讨论】:

标签: 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2016-04-08
    • 2019-08-19
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    相关资源
    最近更新 更多