使用XPathFactory评估Xpath属性

时间:2016-11-21 14:48:39

标签: java xml xpath rest-assured

我想尝试做一些非常简单的事情我认为,只需断言Xpath节点的属性是特定值。该节点没有值,只有一个属性值如下: - <ControlResponse Success="true"/>(将返回&#34; true&#34;或&#34; false&#34;)

<?xml version="1.0" encoding="UTF-8"?><tag0:AAA_ControlRS xmlns:tag0="http://www.xmltravel.com/fab/2002/09" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Target="test"     Version="2002A" xsi:type="AAA_ControlRS">
<tag0:TestInfo TestId="THFTEST"/>
<tag0:SessionInfo CreateNewSession="true"/>
<AAASessionId="8IzujBAVOPVQrO1ySpNBoJ9x"/>
<tag0:ControlResponse Success="true"/>
</tag0:AAA_ControlRS>

这是我的代码:

//REQUEST
    String controlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n...
//bunch of xml here";

   //RESPONSE
    String myControlResponse = given().
            when().
            request().
            contentType("text/xml").
            body(myControlRequest).
            when().post().andReturn().asString();

    //Parse response and get relevant node via Xpath
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    Document doc;

    try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse(new InputSource((new StringReader(myControlResponse))));

        //Xpath Factory Object
        XPathFactory xPathFactory = XPathFactory.newInstance();

        //Xpath Object
        XPath xpath = xPathFactory.newXPath();

        String controlResponse = getNodeValue(doc, xpath);

        assertEquals("true", controlResponse);


    } catch (ParserConfigurationException | org.xml.sax.SAXException | IOException e) {
        e.printStackTrace();
    }
}

private static String getNodeValue(Document doc, XPath xpath) {
    String controlResponse = null;
    try {
        XPathExpression expr =
                xpath.compile("//ControlResponse/@Success");
        controlResponse = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return controlResponse;
}

当我期望String&#34; true&#34;时,xpath的计算结果为null。我想获得属性值并声明它是否包含字符串&#34; true&#34;或&#34; false&#34;

有没有更简单的方法来实现我想要做的事情?

1 个答案:

答案 0 :(得分:2)

要获取属性值,请使用//ControlResponse/@Success作为XPath表达式。

如果命名空间问题妨碍您,请使用//*[local-name()="ControlResponse"]/@Success进行快速检查,如果问题与命名空间有关。

使用不相关的样本文档的示例:

> cat ~/test.xml
<root><foo bar="true"/></root>
> xmllint --xpath '//foo/@bar' ~/test.xml
 bar="true"

如果在您的情况下这不能按预期工作,请显示足够的XML文档,表明问题可以重现。