根据属性从xml中删除

时间:2010-08-06 12:01:48

标签: php xml

我的xml文件名为cgal.xml

<?xml version="1.0"?>
<item>
  <name><![CDATA[<img src="event_pic/pic1.jpg" />CALENDAR]]></name>
  <description title="NAM ELIT AGNA, ENDRERIT SIT AMET, TINCIDUNT AC." day="13" month="8" year="2010" id="15"><![CDATA[<img src="events/preview/13p1.jpg" /><font size="8" color="#6c6e74">In Gladiator, victorious general Maximus Decimus Meridias has been named keeper of Rome and its empire by dying emperor Marcus Aurelius, so that rule might pass from the Caesars back to the people and Senate. Marcus\' neglected and power-hungry son, Commodus, has other ideas, however. Escaping an ordered execution, Maximus hurries back to his home in Spain, too l</font>]]></description>
</item>

我的PHP函数是: -

$doc = new DOMDocument;
            $doc->formatOutput = TRUE;
            $doc->preserveWhiteSpace = FALSE;

$doc->simplexml_load_file('../cgal.xml');
         foreach($doc->description as $des)
            {
                if($des['id'] == $id) {
                    $dom=dom_import_simplexml($des);
                    $dom->parentNode->removeChild($dom);
                }
            }
            $doc->save('../cgal.xml');

id动态传递

我想根据id

删除节点

2 个答案:

答案 0 :(得分:0)

您无需从SimpleXml加载或导入XML。您可以直接使用DOM加载它。此外,您可以使用与问题updatin xml in php中相同的方式删除节点。只需将XPath查询更改为

即可
$query = sprintf('//description[@id="%s"]', $id);

$query = sprintf('/item/description[@id="%s"]', $id);

如果您的XML针对实际将id定义为XML ID的DTD或Schema进行验证,您也可以使用getElementById而不是XPath。这在Simplify PHP DOM XML parsing - how?中解释。

答案 1 :(得分:0)

嗯,首先,没有DomDocument::simplexml_load_file()方法。要么使用dom文档,要么不要......所以使用DomDocument:

$doc = new DomDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;

$doc->loadXml(file_get_contents('../cgal.xml'));

$element = $doc->getElementById($id);
if ($element) {
    $element->parentNode->removeChild($element);
}

那应该为你做...

修改

正如戈登指出的那样,这可能行不通(我试过了,但并不是所有的时间)......所以,你可以:

$xpath = new DomXpath($doc);
$elements = $xpath->query('//description[@id="'.$id.'"]');
foreach ($elements as $element) { 
    $element->parentNode->removeChild($element);
}

或者,使用SimpleXML,您可以递归每个节点(性能更低,但更灵活):

$simple = simplexml_load_file('../cgal.xml', 'SimpleXmlIterator');
$it = new RecursiveIteratorIterator($simple, RecursiveIteratorIterator::SELF_FIRST);
foreach ($it as $element) {
    if (isset($element['id']) && $element['id'] == $id) {
        $node = dom_import_simplexml($element);
        $node->parentNode->removeChild($node);
    }
}