简体   繁体   English

使用xpath查询返回子节点

[英]Return child nodes using xpath query

I'm trying to return all the "field" children of the node "core" below: 我试图返回下面节点“ core”的所有“ field”子元素:

<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

I have the following PHP: 我有以下PHP:

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

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

Something like this works for retrieving a specific "field" and getting it's index: 这样的事情适用于检索特定的“字段”并获取其索引:

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

I've tried queries like the following using all sorts of examples on the net. 我已经使用各种示例在网上尝试了以下查询。 None of them worked: 他们都没有工作:

$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");

Ultimately, what I'm trying to achieve is returning all "field" nodes under "core", loop through them, and create an array from their index and term. 最终,我想要实现的是返回“核心”下的所有“字段”节点,循环遍历它们,并根据其索引和术语创建一个数组。 For example: 例如:

$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",
);

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

It might be the namespace that was tripping you up; 可能是名称空间使您感到困惑。 you were also not querying the correct attribute (you were looking at index , but the URLs are in term ). 您也没有查询正确的属性(您在查看index ,但是URL在term )。 Try this code: 试试这个代码:

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";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM