XPath processor output as string

一曲冷凌霜 提交于 2020-01-17 01:29:12

问题


Standard XPath processing in java with javax.xml.xpath works like this:

  1. I provide name for xml to process
  2. I provide xpath expression as a string.
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!