【发布时间】:2013-05-30 22:16:10
【问题描述】:
我将 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 中有一种方法可以解析字符串而不是文档,那也可以。
【问题讨论】:
-
-1:“没用”可能是您可以在问题中发布的最无用的内容。 什么没用?是不是编译失败了?如果是,请将 整个 编译输出粘贴到您的问题中。它抛出异常了吗?如果是,请将 整个 堆栈跟踪粘贴到您的问题中。它做了别的什么吗?如果是,请描述您的预期以及结果与预期有何不同。
-
抛出异常(无法从元素转换为文档)
-
你读过@kdgregory 写的什么吗? 它抛出异常了吗?如果是,请将整个堆栈跟踪粘贴到您的问题中
-
编辑并抛出异常
标签: java exception xpath document domxpath