为了账号安全,请及时绑定邮箱和手机立即绑定

SimpleXML:根据子元素的内容选择父节点

SimpleXML:根据子元素的内容选择父节点

PHP
胡说叔叔 2023-04-02 10:39:46
这应该是一件容易的事,但我只是没有让它工作:在下面的代码片段中,我想选择具有值为“Categoryname2”的子节点<WebFilterCategory>的节点:<Name><?php$xmlstring = <<<XML<?xml version="1.0" encoding="UTF-8"?><Request>  <Login>    <UserName>admin</UserName>    <Password>admin</Password>  </Login>  <Set Operation="get">    <WebFilterCategory transactionid="">      <Name>Categoryname1</Name>      <Classification>Objectionable</Classification>      <DomainList>        <Domain>example1.com</Domain>        <Domain>example2.com</Domain>      </DomainList>    </WebFilterCategory>    <WebFilterCategory transactionid="">        <Name>Categoryname2</Name>        <Classification>Objectionable</Classification>        <DomainList>            <Domain>example1.org</Domain>            <Domain>example2.org</Domain>        </DomainList>    </WebFilterCategory>  </Set></Request>XML;$xml = simplexml_load_string( $xmlstring ) or die("Error: Cannot create object");foreach ($xml->query('//WebFilterCategory/Name[contains(., "Categoryname2")]') as $category) {    print_r($xmlstring);}?>可能还有一个更精简的查询来获得所需的结果。
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

你要找的方法query不是xpath


然后您可以更新路径以匹配 Name 包含的 WebFilterCategoryCategoryname2


//WebFilterCategory[Name[contains(., "Categoryname2")]]' 

更新代码


$xml = simplexml_load_string( $xmlstring ) or die("Error: Cannot create object");

foreach ($xml->xpath('//WebFilterCategory[Name[contains(., "Categoryname2")]]') as $category) {

    print_r($category);

}

输出


SimpleXMLElement Object

(

    [@attributes] => Array

        (

            [transactionid] => 

        )


    [Name] => Categoryname2

    [Classification] => Objectionable

    [DomainList] => SimpleXMLElement Object

        (

            [Domain] => Array

                (

                    [0] => example3.org

                    [1] => example2.org

                )


        )


)


查看完整回答
反对 回复 2023-04-02
  • 1 回答
  • 0 关注
  • 76 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信