如何从字符串中加载XML中的org.w3c.dom.Document? [英] How do I load an org.w3c.dom.Document from XML in a string?
问题描述
我在字符串中有一个完整的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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!