我正在尝试从一个XML字符串创建一个org.w3c.dom.Document。我使用此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,一个使用Java 6的JSF实现。用于避免与同名的Xpage相关类混淆的Document类的全名。
答案 0 :(得分:3)
不要依赖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>
答案 1 :(得分:1)
您可以尝试使用此:http://www.wissel.net/blog/downloads/SHWL-8MRM36/ $ File / SimpleXMLDoc.java