加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-26 16:01:48 所属栏目:PHP 来源:互联网
导读:我正在使用 PHP和XPath连接到基于远程XML的API.来自服务器的示例响应如下所示. OTA_PingRS Success / EchoDataThis is some test data/EchoData /OTA_PingRS 您可以看到没有起始标记 Success那么如何搜索 Success /的存在?使用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

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读