7

DOM拡張機能を使用して、xml名前空間を含むxmlファイルを解析しています。名前空間宣言は他の属性と同じように扱われると思いましたが、私のテストは一致していないようです。私はこのように始まる文書を持っています:

<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:syn="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:prism="http://purl.org/rss/1.0/modules/prism/"
    xmlns:admin="http://webns.net/mvcb/"
    >

そして、このようなテストコード:

$doc = new DOMDocument();
$doc->loadXml(file_get_contents('/home/soulmerge/tmp/rss1.0/recent.xml'));
$root = $doc->documentElement;
var_dump($root->tagName);
# prints 'string(7) "rdf:RDF"'
var_dump($root->attributes->item(0));
# prints 'NULL'
var_dump($root->getAttributeNode('xmlns'));
# prints 'object(DOMNameSpaceNode)#3 (0) {}'

したがって、質問は次のとおりです。

  1. 誰かが私がのドキュメントをどこで見つけることができるか知っていますDOMNameSpaceNodeか?php.netで検索しても、有用な結果は得られません。
  2. そのDOMElementからすべての名前空間宣言を抽出するにはどうすればよいですか?
4

2 に答える 2

12

より直接的な方法がない限り、XPathとその名前空間軸を使用できます。
例えば

<?php
$doc = new DOMDocument;
$doc->loadxml('<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:syn="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:prism="http://purl.org/rss/1.0/modules/prism/"
    xmlns:admin="http://webns.net/mvcb/"
    >
...
</rdf:RDF>');
$context = $doc->documentElement;

$xpath = new DOMXPath($doc);
foreach( $xpath->query('namespace::*', $context) as $node ) {
  echo $node->nodeValue, "\n";
}

プリント

http://www.w3.org/XML/1998/namespace
http://webns.net/mvcb/
http://purl.org/rss/1.0/modules/prism/
http://purl.org/rss/1.0/modules/syndication/
http://purl.org/dc/elements/1.1/
http://purl.org/rss/1.0/modules/taxonomy/
http://purl.org/rss/1.0/
http://www.w3.org/1999/02/22-rdf-syntax-ns#

edit and btw: I haven't found documentation for DOMNameSpaceNode either. But you can "deduct" (parts of) its functionality from the source code in ext/dom/php_dom.c
It doesn't seem to expose any methods and exposes the properties

"nodeName", "nodeValue", "nodeType",
"prefix", "localName", "namespaceURI",
"ownerDocument", "parentNode"

all handled by the same functions as the corresponding DOMNode properties.

于 2010-03-18T14:13:05.040 に答える
5

Note, that

echo $root->getAttributeNode('xmlns')->nodeValue . "\n";
echo $root->getAttribute('xmlns') . "\n";
echo $root->getAttribute('xmlns:syn') . "\n";

all work as expected, and print out

http://purl.org/rss/1.0/
http://purl.org/rss/1.0/
http://purl.org/rss/1.0/modules/syndication/

because DOMNameSpaceNode is a Node, not a NodeCollection.

Just clarifying, that, unless something in PHP DOM extension changes, XPath (as explained by VolkerK) is the only native way to get all the namespaces, regardless of documentation.

于 2011-06-27T16:35:58.847 に答える