tags:

views:

36

answers:

1

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

But it is not working.

+1  A: 

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>
Gordon