簡體   English   中英

使用xpath查詢返回子節點

[英]Return child nodes using xpath query

我試圖返回下面節點“ 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

我有以下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",
);

任何幫助,將不勝感激。 謝謝。

可能是名稱空間使您感到困惑。 您也沒有查詢正確的屬性(您在查看index ,但是URL在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";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM