douchiwan1503 2010-02-01 23:24
浏览 92
已采纳

在PHP上使用xpath:如何选择第一个孩子?

I have an XML structure like this one:

<layout>
    <pattern> ... </pattern>
    <row> ... </row>
</layout>

How can I select the first node of <layout> by its index, using XPath?

w3schools indicates syntax similar to /bookstore/book[1]/title, but then says:

There is a problem with this. The example above shows different results in IE and other browsers.

IE5 and later has implemented that [0] should be the first node, but according to the W3C standard it should have been [1]!!

A Workaround!
To solve the [0] and [1] problem in IE5+, you can set the SelectionLanguage to XPath.

But that's client-specific. The PHP manual isn't very clear about this either.

  • 写回答

1条回答 默认 最新

  • dongrui6787 2010-02-01 23:37
    关注

    As Felix said: What about trying?

    $l = new SimpleXMLElement('<layout>
      <pattern> ... </pattern> 
      <row> ... </row>  
    </layout>');
    foreach($l->xpath('/layout/*[1]') as $n) {// yeah yeah, it's only one....
      echo $n->getName();
    }
    

    prints pattern. (php 5.3.1/win32/php.net build)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?