php – 如何使用XPath检查节点是否存在

我正在使用 PHP和XPath连接到基于远程XML的API.来自服务器的示例响应如下所示.
<OTA_PingRS>
        <Success />
        <EchoData>This is some test data</EchoData>
    </OTA_PingRS>

您可以看到没有起始标记< Success>那么如何搜索< Success />的存在?使用Xpath?

谢谢
西蒙

<成功/> element是 empty element,意思是没有价值.它是开始和结束标记.

你可以test for existence of nodes with the XPath function boolean()

The boolean function converts its argument to a boolean as follows:

  • a number is true if and only if it is neither positive or negative zero nor NaN
  • a node-set is true if and only if it is non-empty
  • a string is true if and only if its length is non-zero
  • an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type

要使用DOMXPath执行此操作,您需要使用DOMXPath::evaluate()方法,因为它将返回一个类型化结果,在本例中为布尔值:

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

$xpath = new DOMXPath($dom);
$successNodeExists = $xpath->evaluate('boolean(/OTA_PingRS/Success)');

var_dump($successNodeExists); // true

demo

当然,您也可以只查询/ OTA_PingRS / Success并查看返回的DOMNodeList中是否有结果:

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

$xpath = new DOMXPath($dom);
$successNodeList = $xpath->evaluate('/OTA_PingRS/Success');

var_dump($successNodeList->length);

demo

你也可以使用SimpleXML

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$nodeCount = count(simplexml_load_string($xml)->xpath('/OTA_PingRS/Success'));

var_dump($nodeCount); // 1

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...