无法从字符串创建XML文档

2022-03-28 00:00:00 java xpages

我正在尝试创建一个org.w3c.dom.Document形式的XML字符串。我用这个How to convert string to xml file in java作为基础。我没有得到例外,问题是我的文档总是空的。XML是系统生成的,格式良好。我希望将其转换为Document对象,以便可以添加新节点等。

public static org.w3c.dom.Document stringToXML(String xmlSource) throws Exception {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

InputStream input = IOUtils.toInputStream(xmlSource); //uses Apache commons to obtain InputStream
BOMInputStream bomIn = new BOMInputStream(input); //create BOMInputStream from InputStream
InputSource is = new InputSource(bomIn); // InputSource with BOM removed

Document document = builder.parse(new InputSource(new StringReader(xmlSource)));
Document document2 = builder.parse(is);
System.out.println("Document=" + document.getDoctype()); // always null
System.out.println("Document2=" + document2.getDoctype()); // always null

return document;
}

我尝试过这些方法:我创建了一个BOMInputStream,认为BOM导致转换失败。我认为这是我的问题,但是将BOMInputStream传递给InputSource并没有什么不同。我甚至尝试传递一个由简单XML和NULL组成的文字字符串。toString方法返回[#document:null]

我使用的是XPages,这是一个使用Java6的jsf实现。用于避免念力与Xpage相关类同名的Document类的全名。


解决方案

不要依赖toString告诉您的内容。它提供它认为对当前类有用的诊断信息,在本例中,它就是.

"["+getNodeName()+": "+getNodeValue()+"]";

这对你没有帮助。相反,您需要尝试将模型转换回String,例如.

String text
        = "<fruit>"
        + "<banana>yellow</banana>"
        + "<orange>orange</orange>"
        + "<pear>yellow</pear>"
        + "</fruit>";

InputStream is = null;
try {
    is = new ByteArrayInputStream(text.getBytes());
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = builder.parse(is);
    System.out.println("Document=" + document.toString()); // always null

    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    tf.setOutputProperty(OutputKeys.METHOD, "xml");
    tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    ByteArrayOutputStream os = null;
    try {

        os = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(document);
        StreamResult sr = new StreamResult(os);
        tf.transform(domSource, sr);

        System.out.println(new String(os.toByteArray()));

    } finally {
        try {
            os.close();
        } finally {
        }
    }

} catch (ParserConfigurationException | SAXException | IOException | TransformerConfigurationException exp) {
    exp.printStackTrace();
} catch (TransformerException exp) {
    exp.printStackTrace();
} finally {
    try {
        is.close();
    } catch (Exception e) {
    }
}

哪些输出.

Document=[#document: null]
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<fruit>
    <banana>yellow</banana>
    <orange>orange</orange>
    <pear>yellow</pear>
</fruit>

相关文章