如何将包含XML格式内容的String转换为JDom文档。
我正在尝试下面的代码:
String docString = txtEditor.getDocumentProvider().getDocument(
txtEditor.getEditorInput()).get();
SAXBuilder sb= new SAXBuilder();
doc = sb.build(new StringReader(docString));
任何人都可以帮我解决上述问题。 在此先感谢!!
答案 0 :(得分:14)
这就是你通常将xml解析为Document
的方法try {
SAXBuilder builder = new SAXBuilder();
Document anotherDocument = builder.build(new File("/some/directory/sample.xml"));
} catch(JDOMException e) {
e.printStackTrace();
} catch(NullPointerException e) {
e.printStackTrace();
}
如果您有字符串,可以将其转换为InputStream然后传递
String exampleXML = "<your-xml-string>";
InputStream stream = new ByteArrayInputStream(exampleXML.getBytes("UTF-8"));
Document anotherDocument = builder.build(stream);
对于各种参数,builder.build()支持您可以浏览api docs
答案 1 :(得分:8)
这是一个常见问题解答,其中的答案比实际常见问题解答更容易理解:How do I build a document from a String?
所以,我创建了issue #111
对于它的价值,我之前已针对这种情况改进了错误消息(请参阅the previous issue #63,现在您应该出现错误消息:
MalformedURLException mx = new MalformedURLException(
"SAXBuilder.build(String) expects the String to be " +
"a systemID, but in this instance it appears to be " +
"actual XML data.");
底线是你应该使用的:
Document parseddoc = new SaxBuilder().build(new StringReader(myxmlstring));
rolfl