如何将XML(String)转换为有效的文件?

Muh*_*aat 0 java xpath document exception domxpath

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

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

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


        return  sXml;

    } 
Run Code Online (Sandbox Code Playgroud)

但是,如果我想转换整个XML文件怎么办?我尝试了投射,但它没有工作,因为你无法从元素转换为文档(抛出异常):

例外情况:

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to org.w3c.dom.Document
Run Code Online (Sandbox Code Playgroud)

代码 :

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

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


        return (Document) sXml;

    } 
Run Code Online (Sandbox Code Playgroud)

我也尝试了这个但是没有用:

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

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


        return  sXml;

    } 
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能解决这个问题?如果在XPath中有一种解析String而不是文档的方法,它也没问题.

fGo*_*fGo 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)));  
}  
Run Code Online (Sandbox Code Playgroud)