一尘不染

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

java

我在字符串中有一个完整的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;
}

阅读 229

收藏
2020-09-09

共1个答案

一尘不染

在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()));
}
2020-09-09