簡體   English   中英

使用 PHP DOM 查找 XML 中是否存在元素

[英]Find if an element exists in XML using PHP DOM

我有一個 dom 元素,我想查找其中是否存在特定的子元素。

我的節點是這樣的:

    <properties>
        <property name="a-random-neme" option="option2" >value1</property>
        <property name="another-random-name">V2</property>
        <property name="yet-another-random-name" option="option5" >K3</property>
    </properties>

在 php 中,它由 dom object 引用

$properties_node;

在 php 代碼的另一部分中,我想檢查我要添加的數據是否已經存在

    $datum = [ 'name'=>'yet-another-random-name', 'value'=>'K3'];
    //NOTE: If other attributes exists I want to keep them
    $prop=$dom->createElement('property',$datum['value']);
    $prop->setAttribute('name', $datum['name']);

    if(prop_list_contains($properties-node,$prop,['name']))
        $properties_node->appendChild($prop);
    else
        echo "not adding element, found\n";

現在我想做

    /**
     @param $properties_node reference to the existing dom object
     @param $prop the new element I want to add
     @param $required_matches an array containing the name of the attributes that must match

     @return matching element if match is found, false otherweise 
    */
    function prop_list_contains(&$properties_node,$prop,array $required_matches){
    // here I have no Idea how to parse the document I have

      return false
    }

需求:

not adding element, found

我能想到的最簡單的方法是使用 XPath 來檢查節點是否已經存在。

假設您將只使用 1 個元素進行匹配(更多可能,但要復雜得多)。 這首先從新節點中提取值,然后使用 XPath 檢查當前數據中是否已存在匹配值。

此過程的主要內容是確保您使用正確的上下文進行搜索。 這實際上是要搜索的內容,首先它使用新元素,然后使用當前元素來檢查它。

function prop_list_contains(DOMXPath $xp, $properties_node, $prop, 
        array $required_matches){
    // Extract value from new node
    $compare = $xp->evaluate('string(@'.$required_matches[0].')', $prop);
    // Check for the value in the existing data
    $xpath = 'boolean(./property[@'. $required_matches[0] . ' = "' . $compare . '"])';

    return ( $xp->evaluate($xpath, $properties_node) );
}

這也意味着您需要創建 XPath object 才能傳入...

$xp = new DOMXPath($dom);

這樣可以節省每次創建它。

同樣,如果節點存在,這將返回true ,因此您需要將測試更改為使用! ...

if( ! prop_list_contains($xp, $properties_node,$prop,['name'])) {
    $properties_node->appendChild($prop);
}
else    {
    echo "not adding element, found\n";
}

暫無
暫無

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

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