微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/php/240289.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐