How to delete an element from an XML tree where at

2019-06-05 13:48发布

问题:

So I want to delete a child from an XML string where an attribute is a specific value.

For Example:

<xml>
  <note url="http://google.com">
   Values
  </note>
  <note url="http://yahoo.com">
   Yahoo Values
  </note>
</xml>

So how would I delete the note node with attribute http://yahoo.com as the string for the URL?

I'm trying to do this in PHP Simple XML

Oh and also I'm loading it in as an XML Object with the SimpleXML_Load_String function like this:

$notesXML = simplexml_load_string($noteString['Notes']);

回答1:

SimpleXML does not have the remove child node feature,
there are cases you are can do How to deleted an element inside XML string?
but is depend on XML structure

Solution in DOMDocument

$doc = new DOMDocument;
$doc->loadXML($noteString['Notes']);

$xpath = new DOMXPath($doc);
$items = $xpath->query( 'note[@url!="http://yahoo.com"]');

for ($i = 0; $i < $items->length; $i++)
{
  $doc->documentElement->removeChild( $items->item($i) );
}


回答2:

It is possible to remove nodes with SimpleXML by using unset(), though there is some trickery to it.

$yahooNotes = $notesXML->xpath('note[@url="http://yahoo.com"]');
// We know there is only one so access it directly
$noteToRemove = $yahooNotes[0];
// Unset the node. Note: unset($noteToRemove) would only unset the variable
unset($noteToRemove[0]);

If there are multiple matching nodes that you wish to delete, you could loop over them.

foreach ($yahooNotes as $noteToRemove) {
    unset($noteToRemove[0]);
}