删除xml节点&&案例节点中的数据是否相同?

时间:2010-12-30 10:51:18

标签: php

$xml = '<books>    
            <book>
                <qty>12</qty>
                <title>C++</title>
            </book>
            <book>
                <qty>21</qty>
                <title>PHP</title>
            </book>    
        </books>    
        <books>        
            <book>  
            <qty>21</qty>
            <title>JAVA</title>
            </book>    
        </books>';


$str = '<content>'.$xml.'</content>';

$doc = new DOMDOcument;
$doc->loadxml($str);

$xpath = new DOMXpath($doc);

$arr = array(
    array('12;C++', '21;PHP')
);

# Remove elements based on qty and title
foreach($arr as $items) {
    foreach($items as $item) {
        list($qty, $title) = explode(';', $item);
        foreach($xpath->query('/content/books/book[title="'.$title.'"][qty="'.$qty.'"]') as $book) {
            $book->parentNode->removeChild($book);
        }
    }
}

# Remove empty <books>
foreach($xpath->query('books[count(book)=0]') as $empty) {
    $empty->parentNode->removeChild($empty);
}
header('Content-type: text/xml');
echo $doc->savexml();

输出:

<content>
    <books>
        <book>
            <qty>21</qty>
            <title>JAVA</title>
        </book>
    </books>
</content>

但是如果xml包含相同的数据:

$xml = '<books>    
            <book>
                <qty>12</qty>
                <title>C++</title>
            </book>
            <book>
                <qty>21</qty>
                <title>PHP</title>
            </book>    
        </books>    
        <books>        
            <book>  
                <qty>21</qty>
                <title>PHP</title> <!-- here the same data-->
            </book>    
        </books>';

它应该得到这样的输出:

<content>
    <books>
        <book>
            <qty>21</qty>
            <title>PHP</title>
        </book>
    </books>
</content>

为什么要删除我的所有节点?我得到了

<content>
</content>

1 个答案:

答案 0 :(得分:1)

如果您只想删除第一个匹配项,只需将break添加到搜索元素的循环中:

# Remove elements based on qty and title
foreach($arr as $items) {
    foreach($items as $item) {
        list($qty, $title) = explode(';', $item);
        foreach($xpath->query('/content/books/book[title="'.$title.'"][qty="'.$qty.'"]') as $book) {
            $book->parentNode->removeChild($book);
            break; // <- Handle only the first match
        }
    }
}