问题描述
我有一个完整的字符串形式的 XML 文档,并且想要一个 Document
对象.谷歌会出现各种垃圾.什么是最简单的解决方案?(在 Java 1.5 中)
I have a complete XML document in a string and would like a Document
object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)
解决方案 多亏了 Matt McMinn,我已经确定了这个实现.它具有适合我的输入灵活性和异常粒度级别.(很高兴知道错误是来自格式错误的 XML - SAXException
- 还是错误的 IO - IOException
.)
Solution Thanks to Matt McMinn, I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException
- or just bad IO - IOException
.)
public static org.w3c.dom.Document loadXMLFrom(String xml)
throws org.xml.sax.SAXException, java.io.IOException {
return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes()));
}
public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is)
throws org.xml.sax.SAXException, java.io.IOException {
javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
}
catch (javax.xml.parsers.ParserConfigurationException ex) {
}
org.w3c.dom.Document doc = builder.parse(is);
is.close();
return doc;
}
推荐答案
这在 Java 1.5 中对我有用 - 为了可读性,我去掉了特定的异常.
This works for me in Java 1.5 - I stripped out specific exceptions for readability.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;
public Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}
这篇关于如何从字符串中的 XML 加载 org.w3c.dom.Document?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!