问题
Standard XPath processing in java with javax.xml.xpath works like this:
- I provide name for xml to process
- I provide xpath expression as a string.
- I gain answer stored as a list of nodes, or eventually as a single value depending on what type of output I select.
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?
回答1:
XPath.evaluate(expression, inputSource) seems to do what you want.
Edit: Here's some sample code:
String xml = "<foo><bar>text</bar></foo>";
Reader reader = new StringReader(xml);
InputSource inputSource = new InputSource(reader);
XPath xpath = XPathFactory.newInstance().newXPath();
System.out.println(xpath.evaluate("/foo/bar", inputSource));
Edit: this question indicates that there is no java api that can be instantly used to meet your goals. If you're testing XML, then you might want to have a look at XmlUnit
回答2:
If you use
xPathExpression.evaluate(document);
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);
EDIT 1: Here's a SO article on converting a NodeList to an XML document and printing it.
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);
}
来源:https://stackoverflow.com/questions/12109564/xpath-processor-output-as-string