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).

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?