0

I am generating an XML File on the fly and want to remove certain childs by their attribute name.

For example: Data.xml

<root>
<item name="item-1">
  <sub1>some text</sub1>
  <sub2>etc.</sub2>
</item>
<item name="item-2">
  <sub1>some different text</sub1>
  <sub2>etc.</sub2>
</item>
</root>

Now I am trying to remove an element by the attribute name. (i.e. "item-1")

That's how my XML Doc and my elements are set:

$doc = new DOMDocument('1.0', 'utf-8');
$root = $doc->createElement("root");
$doc->appendChild($root);

// Foreach... {

$item = $doc->createElement("item");
$item->setAttributeNode(new DOMAttr('name', 'item-'.$i));
$root->appendChild($item);

}

$doc->save("Data.xml")

I'd love to have something like: $doc->removeElementByAttributeValue("item-1"), but I can't find the trick :-(

Mike
  • 2,686
  • 7
  • 44
  • 61

1 Answers1

1

Use xpath to find the node:

//item[@name='item-1']

which'll return the exact matching node, which you can then pass into the removeChild call

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Hey Marc, I tried `$xpath = new DOMXPath($doc); $query = '//item[@name="item-1"]'; $emps = $xpath->query($query); print_r($emps);` but it doesn't show up anything except DOMNodeList Object ( ). Is that how it should work? – Mike Oct 23 '11 at 20:11