【发布时间】:2013-06-24 07:14:57
【问题描述】:
我正在使用 org.w3c.dom 库将 XML Elements 和 Documents 存储在我创建的 Item 类中。有时我需要使用setAttribute 来配置Elements 以供以后解析(由用.NET 编写的服务器完成)。我最初使用 JDOM,但由于 XPath 和 selectSingleNode 已被弃用,它不再具有我需要的功能。
我的变量声明为:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document outDom = null;
db = dbf.newDocumentBuilder();
outDom = (Document) db.parse("<Empty/>");
Node fault_node = null;
而错误来自以下行:
fault_node = (Node) xp.evaluate(Item.XPathFault, outDom, XPathConstants.NODE);
这是在 Item 之外的另一个类中(HttpServerConnection,如果重要的话),但 Item.XPathFault 在 Item 中声明为
public static final String XPathFault = "/" + Soap.EnvelopeBodyFaultXPath;
Soap 包含定义
static final String SoapEnvUri = "http://schemas.xmlsoap.org/soap/envelope/";
private static final String SoapNamespaceCheck = "namespace-uri()='" + SoapEnvUri + "' or namespace-uri()=''";
static final String EnvelopeXPath = "*[local-name()='Envelope' and (" + SoapNamespaceCheck + ")]";
static final String BodyXPath = "*[local-name()='Body' and (" + SoapNamespaceCheck + ")]";
static final String FaultXPath = "*[local-name()='Fault' and (" + SoapNamespaceCheck + ")]";
static final String EnvelopeBodyXPath = EnvelopeXPath + "/" + BodyXPath;
static final String EnvelopeBodyFaultXPath = EnvelopeBodyXPath + "/" + FaultXPath;
问题是当我在模拟器上运行程序时,我得到了错误:
javax.xml.xpath.XPathExpressionException: javax.xml.transform.TransformerException: Unknown error in XPath.
at org.apache.xpath.jaxp.XPathImpl.evaluate(XPathImpl.java:295)
我想从 XPath.evaluate 函数中得到一个 selectSingleNode,它在 JDOM2 中已被弃用,在 w3c.dom 中不存在。虽然老实说,我不确定我是否使用了正确的功能。但我知道错误来自哪里,但我不知道为什么。
编辑:我找到了答案
原来我的问题是代码db.parse("<Empty/>"); 和其他类似的语句。
我误解了parse 的功能。当传递一个字符串时,它假定字符串是要读取的 XML 文件的路径/位置。当我将实际的 XML 作为字符串传递给方法时,这会导致错误。如果parse 传递了InputStream,它将以XML 格式读取流的内容。
我通过更改修复了我的程序
outDom = (Document) db.parse("<Empty/>");
稍微长一点
InputStream is = new ByteArrayInputStream("<Empty />".getBytes());
Document outDom = (Document) builder.parse(is);
【问题讨论】:
-
在所有连接发生后,您是否尝试过检查 XPathFault 的值?也许这会提供一些见解。
-