使用xpath查询返回子节点

时间:2014-09-20 15:34:47

标签: php xpath domdocument

我正在尝试返回以下节点“核心”的所有“字段”子节点:

<archive xmlns="http://rs.tdwg.org/dwc/text/" metadata="eml.xml">
  <core encoding="utf-8" fieldsTerminatedBy="\t" linesTerminatedBy="\n" fieldsEnclosedBy="" ignoreHeaderLines="1" rowType="http://rs.tdwg.org/dwc/terms/Occurrence">
    <files>
      <location>occurrence.txt</location>
    </files>
    <id index="0" />
    <field index="1" term="http://rs.tdwg.org/dwc/terms/class"/>
    <field index="2" term="http://rs.tdwg.org/dwc/terms/maximumDepthInMeters"/>
    <field index="3" term="http://purl.org/dc/terms/language"/>
    <field index="4" term="http://rs.tdwg.org/dwc/terms/coordinatePrecision"/>
    <field index="5" term="http://rs.tdwg.org/dwc/terms/decimalLatitude"/>
 </core>
</archive

我有以下PHP:

$xml = new \DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->load($input_xml);

$xpath = new \DOMXpath($xml);
$xpath->registerNamespace('ns', $xml->documentElement->namespaceURI);

这样的东西适用于检索特定的“字段”并获取它的索引:

$query = $xpath->query("//ns:field[contains(@term, 'http://rs.tdwg.org/dwc/terms/class')]")->item(0);
$url = $query->attributes->getNamedItem("index")->nodeValue;

我在网上使用了各种各样的例子尝试过以下的查询。他们都没有工作:

$children = $xpath->query("//ns:core/field");
$children = $xpath->query("//core/field");
$children = $xpath->query("/core/field");
$children = $xpath->query("/core/*");
$children = $xpath->query("/archive/core/field");
$children = $xpath->query("//ns:core/ns:field");

最终,我想要实现的是返回“核心”下的所有“字段”节点,循环遍历它们,并从它们的索引和术语创建一个数组。例如:

$myArray = array(
    "1" => "http://rs.tdwg.org/dwc/terms/class",
    "2" => "http://rs.tdwg.org/dwc/terms/maximumDepthInMeters",
    "3" => "http://purl.org/dc/terms/language",
);

任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

它可能是绊倒你的命名空间;您也没有查询正确的属性(您正在查看index,但网址位于term)。试试这段代码:

foreach( $xpath->query('/ns:archive/ns:core/ns:field') as $field) {
    if ( $field->attributes->getNamedItem("term")->nodeValue ) {
        echo "URL: " . $field->attributes->getNamedItem("term")->nodeValue . "\n";
    }
}