duanqinqian5299 2017-07-10 12:32
浏览 77

如何使用php Xpath从XML列出所有命名空间

<?xml version="1.0" encoding="US-ASCII" ?>
<main:docs xmlns:admin="someval" xmlns:system="someval" xmlns:links="someval">
    XML content here
</main:docs>

I want to list out namespace used in XML that is xmlns:admin, xmlns:system, xmlns:links.

I tried it like

$doc = new DOMDocument();

$context = $doc->documentElement;

$xpath = new DOMXPath($doc);

$xml = simplexml_load_file("path to xml");

foreach( $xpath->query('namespace::*', $context) as $node ) 
{
  echo $node->nodeName;
}

but no output

  • 写回答

1条回答

  • doumaque6551 2017-07-17 09:20
    关注

    The short answer is, you don't. Most important xmlns:admin is not the namespace but just an alias/prefix. The actual namespaces are the values you replaced with someval.

    SimpleXMLElement::getNamespaces() (from you comment) is a method for debugging only. You should not read the namespaces prefixes from the document, they will only be valid for the current context anyway.

    $xml = <<<'XML'
    <foo:outer xmlns:foo="urn:foo">
      <bar:inner xmlns:bar="urn:bar"/>
    </foo:outer>
    XML;
    
    $outer = new SimpleXMLElement($xml);
    var_dump(
      $outer->getNamespaces()
    );
    var_dump(
      $outer->children('urn:bar')->inner->getNamespaces()
    );
    

    Output:

    array(1) {
      ["foo"]=>
      string(7) "urn:foo"
    }
    array(1) {
      ["bar"]=>
      string(7) "urn:bar"
    }
    

    Namespace definitions are allowed on any element node and you can define a default namespace for elements.

    So you work with the actual namespace URI. Put them into a variable/array on you code. Use SimpleXMLElement::registerXpathNamespace() to register your own prefixes for a namespace (for Xpath expressions).

    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换