从xml文件中删除节点

时间:2010-10-14 11:29:14

标签: php dom xpath

我有一个xml文件

<?xml version="1.0"?>
<category>
  <name>SWEATERS</name>
  <name>WATCHES</name>
  <name>PANTS</name>
  <name>test</name>
  <name>1</name>
</category>

如何使用xpath,xquery和php删除节点<name>test</name>。我用过这段代码

 $name='test;
    $xmlfile="config/shop_categories.xml";
    $xml = simplexml_load_file($xmlfile);
    $target = $xml->xpath('/category[name="'.trim($name).'"]');
    print_r($target[0]);
    if($target == false)
    return; 
    $domRef = dom_import_simplexml($target[0]); //Select position 0 in XPath array
    $domRef->parentNode->removeChild($domRef);
    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($xml->asXML());
    $dom->save($xmlfile);

但它没有用。

1 个答案:

答案 0 :(得分:1)

很确定这是重复的,但我太懒了找不到它。你走了:

$xml = <<< XML
<?xml version="1.0"?>
<category>
  <name>SWEATERS</name>
  <name>WATCHES</name>
  <name>PANTS</name>
  <name>test</name>
  <name>1</name>
</category>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$xPath = new DOMXPath($dom);
foreach($xPath->query('//name[text() = "test"]') as $node) {
    $node->parentNode->removeChild($node);
}
echo $dom->saveXML();

输出:

<?xml version="1.0"?>
<category>
  <name>SWEATERS</name>
  <name>WATCHES</name>
  <name>PANTS</name>

  <name>1</name>
</category>