我在字符串中有一个完整的XML文档,想要一个Document对象。Google会产生各种垃圾。什么是最简单的解决方案?(在Java 1.5中)
解决方案感谢Matt McMinn,我决定完成此实现。对我来说,它具有适当级别的输入灵活性和异常粒度。(很高兴知道错误是来自格式错误的XML- SAXException还是来自错误的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;
}
                  如果可以纠正解决方案,那就太好了。使用String.getByptes和InputStream会带来i18n问题。我的一位朋友从这里获取了代码,这是错误的。幸运的是,findbugs检测到了该问题。erickson提供的正确解决方案是使用InputSource。
                
                
                  
                    —
                    肯尼思·许