[英]Xpath: Check if node doesn't exist
我从我的 webshops API 调用中获取 XML,其结构类似于以下示例:
<Customers>
<Customer>
<Username>userOne</Username>
<Params>
<Param>
<Id>111</Id>
<Name>Param1</Name>
<Value><![CDATA[Param 1 is on]]></Value>
</Param>
<Param>
<Id>112</Id>
<Name>Param2</Name>
<Value><![CDATA[OFF]]></Value>
</Param>
</Params>
</Customer>
<Customer>
<Username>userTwo</Username>
<Params>
<Param>
<Id>111</Id>
<Name>Param1</Name>
<Value><![CDATA[Param 1 is on]]></Value>
</Param>
<Param>
<Id>112</Id>
<Name>Param2</Name>
<Value><![CDATA[OFF]]></Value>
</Param>
</Params>
</Customer>
<Customer>
<Username>userThree</Username>
<Params>
<Param>
<Id>112</Id>
<Name>Param2</Name>
<Value><![CDATA[ON]]></Value>
</Param>
</Params>
</Customer>
它们中有更多参数,因为数量取决于许多外部因素。 当 id"111" 和 id"112" 的值是我正在寻找的值时,我正在尝试获取用户名。 Customers/Customer[Params/Param[Id/text()='111']/Value/text()='Param 1 is on'][Params/Param[Id/text()='112']/Value/text()='OFF']/Username/text()
上面的代码按预期返回“userOne”和“userTwo”。
问题是,Id“111”要么具有值“Param 1 is on”,要么没有值,如果它没有值,它就不会出现在 XML 中。 因此,我需要一个表达式来检查是否不存在具有 id“111”的节点并且 id“112”的值为“ON”。
不幸的是,Xpath 对我来说真的很新,我找不到专门检查节点是否不存在的方法。
根据定义,当转换为布尔值时,节点集为真,并且仅当它具有元素时才为真( https://www.w3.org/TR/xpath-31/#dt-ebv )。 这样,值元素的存在检查看起来像
fn:boolean(Customers/Customer[Params/Param[Id/text()='111']/Value)
或者如果您想将其作为第三种选择包含在您的支票中
Customers/Customer[Params/Param[Id/text()='111' and not ./Value]
XPath count(expr)
可用于检查条件是否缺失
Customers/Customer[count(Params/Param[Id/text()='111' and Value/text()='Param 1 is on']) = 0 and Params/Param[Id/text()='112']/Value/text()='ON']/Username/text()
所以这部分检查那个节点不存在count(Params/Param[Id/text()='111' and Value/text()='Param 1 is on']) = 0
或者count(Params/Param[Id/text()='111']) = 0
并且这部分检查其他预期条件Params/Param[Id/text()='112']/Value/text()='ON'
应用于样品退货:
userThree
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.