0

我将 XML 作为字符串,我想将其转换为 DOM 文档以便使用 XPath 对其进行解析,我使用此代码将一个字符串元素转换为 DOM 元素:

public Element convert(String xml) throws ParserConfigurationException, SAXException, IOException{

        Element sXml =  DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()))
                .getDocumentElement();


        return  sXml;

    } 

但是如果我想转换整个 XML 文件呢?我尝试了强制转换,但它不起作用,因为您无法从 Element 转换为 Document(抛出异常):

例外:

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to org.w3c.dom.Document

编码 :

public Document convert(String xml) throws ParserConfigurationException, SAXException, IOException{

        Element sXml =  DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()))
                .getDocumentElement();


        return (Document) sXml;

    } 

我也试过这个但没有奏效:

public Document convert(String xml) throws ParserConfigurationException, SAXException, IOException{

        Document sXml =  DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()));


        return  sXml;

    } 

我能做些什么来解决这个问题?如果在 XPath 中有一种方法可以解析字符串而不是文档,它也可以。

4

1 回答 1

5

也许通过使用这个

public static Document stringToDocument(final String xmlSource)   
    throws SAXException, ParserConfigurationException, IOException {  
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
    DocumentBuilder builder = factory.newDocumentBuilder();  

    return builder.parse(new InputSource(new StringReader(xmlSource)));  
}  
于 2013-06-04T13:30:21.727 回答