我想將包含XML的字符串解析爲Java中的文檔對象。下面是該方法的源代碼:如何將字符串解析爲Java中的XML文檔?
private Document getDocument(String xml) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document doc = null;
try {
doc = builder.parse(new InputSource(new StringReader(xml)));
} catch (SAXException e) {
System.out.println(e.toString());
} catch (IOException e) {
System.out.println(e.toString());
}
return doc;
}
我根據調試器總是爲doc變量的值是
[#document:空]
不任何人都有線索有什麼問題?
謝謝你的時間!
的可能的複製[如何解析包含在Java的XML字符串和檢索的價值根節點?](http://stackoverflow.com/questions/8408504/how-to-parse-a-string-containing-xml-in-java-and-retrieve-the-value-of-the-root) – DimaSan