dongzhuo3376 2017-04-12 14:19
浏览 40
已采纳

当子值匹配时获取父数据

I would like to get parent data when my child value matches with "id22"

<servers>
<someservers>
  <owner>id0</owner>
  <serverCode>fefwewf</serverCode>
  <address>345345</address>
  <authCertHash>efref</authCertHash>
  <authCertHash>erferf=</authCertHash>
  <client>id1</client>
  <client>id22</client>
</someservers>
<someservers>
  <owner>id33</owner>
  <serverCode>f</sewewefrverCode>
  <address>234234234</address>
  <authCertHash>sdfs</authCertHash>
  <client>id27</client>
</someservers>
</server>

Currently im trying as following:

$server = $xml -> xpath('//someservers//client='id22');
echo $server->address;

But it's not working, I get error:

Trying to get property of non-object in...

I hope to get output:

345345
  • 写回答

2条回答 默认 最新

  • doupin5667 2017-04-12 18:30
    关注

    SimpleXMLElement::xpath() only supports Xpath expressions that return an node list, so it can convert them into an array of SimpleXMLElementinstances.

    @andersson already explained that you expression only returns the existence of the specified client element. You need to use a condition. This will return an array with matching SimpleXMLElement objects as the elements.

    $servers = new SimpleXMLElement($xml);
    $server = $servers->xpath('//someservers[client="id22"]')[0];
    echo $server->address;
    

    Output:

    345345
    

    DOMXpath::evaluate() is able to return the scalar value directly:

    $document = new DOMDocument();
    $document->loadXml($xml);
    $xpath= new DOMXpath($document);
    echo $xpath->evaluate('string(//someservers[client="id22"]/address)');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据