【问题标题】:SimpleXML: How do I get other attributes when selecting nodes that contain a namespaced attribute?SimpleXML:选择包含命名空间属性的节点时如何获取其他属性?
【发布时间】:2016-11-09 03:44:46
【问题描述】:

在选择包含命名空间属性的节点时如何获取其他属性?

我有一个带有xlink:href 的SVG,我正在尝试访问id 属性,但是当使用xpath 时,它似乎只返回一个“属性节点”。如何获取实际的“元素节点”?

$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <image id="my-image" xlink:href="http://example.com/image.png" />
    </svg>
');
$xml->registerXPathNamespace('svg', 'http://www.w3.org/2000/svg');
$xml->registerXPathNamespace('xlink', 'http://www.w3.org/1999/xlink');
$images = $xml->xpath('//svg:image/@xlink:href');
foreach ($images as $image) {
    var_dump($image);
}

输出:

object(SimpleXMLElement)#2 (1) {
  ["@attributes"]=>
  array(1) {
    ["href"]=>
    string(28) "http://example.com/image.png"
  }
}

https://3v4l.org/lvILL

【问题讨论】:

    标签: php xpath svg simplexml xml-namespaces


    【解决方案1】:

    好的,我想通了。正确的 xpath 是:

    $images = $xml->xpath('//svg:image[@xlink:href]');
    

    https://3v4l.org/NTcvP

    【讨论】:

      猜你喜欢
      • 2012-11-10
      • 2011-09-28
      • 2014-06-15
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多