我有一个xml字符串,我想只比较选定的节点值并在结果上断言我的测试用例。 例如:我有以下xml字符串
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:requestTransferResponse xmlns:ns2="http://external.interfaces.my.company.com/">
<return>
<ersReference>2017051017472278401000061</ersReference>
<resultCode>0</resultCode>
<resultDescription>SUCCESS</resultDescription>
<receivedAmount>
<currency>BSD</currency>
<value>5500.00</value>
</receivedAmount>
<receiverPrincipal>
<principalId>
<id>SUBDIST1-1</id>
<type>RESELLERID</type>
</principalId>
<principalName>Sub Distributor 1</principalName>
<accounts>
<account>
<accountSpecifier>
<accountId>SUBDIST1-1</accountId>
<accountTypeId>RESELLER</accountTypeId>
</accountSpecifier>
<balance>
<currency>BSD</currency>
<value>985500.00</value>
</balance>
<creditLimit>
<currency>BSD</currency>
<value>0.00000</value>
</creditLimit>
</account>
</accounts>
<status>Active</status>
<msisdn>12420101000</msisdn>
</receiverPrincipal>
<requestedTransferAmount>
<currency>BSD</currency>
<value>5500</value>
</requestedTransferAmount>
<senderPrincipal>
<principalId>
<id>DIST1</id>
<type>RESELLERID</type>
</principalId>
<principalName>Distributor 1</principalName>
<accounts>
<account>
<accountSpecifier>
<accountId>DIST1</accountId>
<accountTypeId>RESELLER</accountTypeId>
</accountSpecifier>
<balance>
<currency>BSD</currency>
<value>1994429.24</value>
</balance>
<creditLimit>
<currency>BSD</currency>
<value>0.00000</value>
</creditLimit>
</account>
</accounts>
<status>Active</status>
<msisdn>12420100000</msisdn>
</senderPrincipal>
</return>
</ns2:requestTransferResponse>
</soap:Body>
</soap:Envelope>
现在我要验证具有XPATH的以下节点的值
1. //receiverPrincipal//balance//value i.e 985500.00
2. //senderPrincipal//balance//value i.e. 1994429.24
其他节点不是必需的。所以我搜索了互联网并找到了XmlUnit库。任何人都可以提示如何使用它来验证xpath节点值吗?
答案 0 :(得分:0)
如果您真的只需要一些可以通过XPath识别的选定文本,那么XMLUnit的XPath支持应该可以工作。
将示例从XMLUnit&#39; github页面(请参阅https://github.com/xmlunit/xmlunit/#asserting-an-xpath-value)翻译成您的第一个要求
XPathEngine xpath = new JAXPXPathEngine();
String content = xpath.evaluate("//receiverPrincipal//balance/value/text()", source);
assertEquals(985500.00, Double.valueOf(content), 1e-3);
如果你确定那里只有一个匹配的XPath。
使用Hamcrest匹配器就像
assertThat(source, EvaluateXPathMatcher.hasXPath("//receiverPrincipal//balance/value/text(),
equalTo("985500.00"))