XPath 处理器输出为字符串 [英] XPath processor output as string
问题描述
Java 中使用 javax.xml.xpath 进行标准 XPath 处理的工作方式如下:
Standard XPath processing in java with javax.xml.xpath works like this:
- 我为要处理的xml提供名称
- 我以字符串形式提供 xpath 表达式.
- 我获得的答案存储为节点列表,或者最终存储为单个值,具体取决于我选择的输出类型.
我需要用 java 编写几个测试,它们基本上应该是这样的:我将 xpath 表达式作为字符串提供,并检查此表达式的 xpath 输出是否等于某个指定的输出(也作为字符串提供).所以我不需要遍历节点树和东西,我只需要获得 xpath 处理器输出作为字符串.有没有办法做到这一点?
I need to write a couple of tests in java which basically should work like this: I provide xpath expression as a string and it checks if xpath output of this expression equals to some specified output(also provided as string). So I dont need traversing through node tree and stuff, I just need to gain xpath processor output as a string. Is there any way to do this?
推荐答案
如果你使用
xPathExpression.evaluate(document);
其中 document
是您的 DOM 文档,然后它将返回它匹配的第一个节点的字符串表示.对于您认为 XPath 正在选择单个文本节点的用例,这可能很好.如果不是这种情况,您可以为从以下位置返回的 NodeList
编写一些 toString()
方法:
where document
is your DOM document, then it will return a string representation of the first node it matches. That's probably fine for the use case where you believe that your XPath is selecting a single text node. If that's not the case, you could write some toString()
method for NodeList
that is returned from:
xPathExpression.evaluate(document, XPathConstants.NODESET);
编辑 1:这是一篇关于转换 NodeListSO 的文章/code> 到 XML 文档并打印它.
EDIT 1: Here's a SO article on converting a NodeList
to an XML document and printing it.
编辑 2:如果您有使用 count
的 XPath 表达式或返回单个值的逻辑运算符,那么您可以捕获抛出的异常并采取适当的操作:
EDIT 2: If you have XPath expressions that use count
or logical operators that return single values, then you could catch the exception thrown and take the appropriate action:
try {
NodeList nodeList = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println(node.getNodeName());
}
} catch (XPathExpressionException e) {
String result = xPathExpression.evaluate(document);
System.out.println(result);
}
这篇关于XPath 处理器输出为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!