java – 如何在字符串中从XML加载org.w3c.dom.Document?

我有一个完整的XML文档在字符串中,并希望一个Document对象。谷歌出现了各种各样的垃圾。什么是最简单的解决方案? (在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;
}
这对我来说在Java 1.5 – 我删除了可读性的特定异常。

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()));
}
http://stackoverflow.com/questions/33262/how-do-i-load-an-org-w3c-dom-document-from-xml-in-a-string

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 如何在字符串中从XML加载org.w3c.dom.Document?