我将 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 中有一种方法可以解析字符串而不是文档,它也可以。