【问题标题】:Get an element from an array using xpath使用 xpath 从数组中获取元素
【发布时间】:2011-09-26 18:38:09
【问题描述】:

我有以下 SimpleXML 对象:

SimpleXMLElement Object
(
[@attributes] => Array
    (
        [status] => ok
    )

[a] => SimpleXMLElement Object
    (
        [b] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [c] => Google
                        [d] => GOOG
                        [e] => http://www.google.com
                    )

                [1] => SimpleXMLElement Object
                    (
                        [c] => Yahoo
                        [d] => YHOO
                        [e] => http://www.yahoo.com
                    )

                [2] => SimpleXMLElement Object
                    (
                        [c] => Microsoft
                        [d] => MSFT
                        [e] => http://www.microsoft.com
                    )

鉴于d 我想得到e - 由于b 是一个数组,有没有办法在不循环整个数组的情况下做到这一点?

<stk status="ok">
<a>
  <b>
    <c>Yahoo</c>
    <d>YHOO</d>
    <e>http://www.yahoo.com</e>
  </b>

  <b>
    <c>Google</c>
    <d>GOOG</d>
    <e>http://www.google.com</e>
  </b>

  <b>
    <c>Microsoft</c>
    <d>MSFT</d>
    <e>http://www.microsoft.com</e>
  </b>
</a>
</stk>

【问题讨论】:

  • XPath: //d/following-sibling::e[1]?
  • 关闭!这实际上是返回所有 e 值。我怎样才能让它返回e 的值,其中d 是,让天,YHOO?
  • 如果你愿意分享底层的 XML,那就更容易分辨了。
  • 更新帖子以显示底层 XML。

标签: php xpath simplexml


【解决方案1】:

您可以使用 XPath 查询来查询 e 元素,这些元素是 b 元素的子元素,其中 d 元素带有文本 YHOO

请记住,SimpleXMLElement::xpath() 将返回一个元素数组,即使 XPath 只找到一个元素:因此 $urls[0] 将获得第一个(唯一的)元素。

$xml  = '<stk status="ok"><a><b><c>Yahoo</c><d>YHOO</d><e>http://www.yahoo.com</e></b><b><c>Google</c><d>GOOG</d><e>http://www.google.com</e></b><b><c>Microsoft</c><d>MSFT</d><e>http://www.microsoft.com</e></b></a></stk>';
$stk  = simplexml_load_string($xml);
$urls = $stk->xpath('/stk/a/b[d="YHOO"]/e');
$yhoo = (string) $urls[0];
echo $yhoo;

【讨论】:

    【解决方案2】:

    遍历所有//d

    对于每一个,评估following-sibling::e[1]

    我认为这就是 Marc B 的意思。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2020-07-17
      • 1970-01-01
      相关资源
      最近更新 更多