开发者

Removing a node from xml file

I have an xml file

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

How i can remove the node <name>test</name> using xpath ,xquery and php. I used this code

 $name='test;
    $xmlf开发者_运维技巧ile="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);

But it is not working.


Pretty sure this is a duplicate, but am too lazy to find it. Here you go:

$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();

Output:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜