2011-09-06 45 views
1

所以我想从属性是特定值的XML字符串中删除子元素。如何从XML树中删除元素,其中属性是简单XML中的特定字符串PHP

例如:

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

那么我将如何删除与属性http://yahoo.com作为字符串的URL的说明节点?

我试图做到这一点在PHP中简单的XML

哦,也是我在加载它作为与SimpleXML_Load_String功能像这样的XML对象:

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

类似的问题:http://stackoverflow.com/questions/262351/remove-a-child-with-a-specific-attribute-in-simplexml-for-php –

+0

你从哪里弄来'$ noteString从? – krummens

回答

2

的SimpleXML没有删除子节点功能,
有这样的情况,你是可以做How to deleted an element inside XML string?
而是依赖于XML结构

解决方案在DOM文档

$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)); 
} 
+0

这工作,这个解决方案也可以工作:http://stackoverflow.com/questions/262351/remove-a-child-with-a-specific-attribute-in-simplexml-for-php – Talon

1

有可能通过使用unset()除去用SimpleXML节点,虽然有一些挂羊头卖狗肉吧。

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

如果您想删除多个匹配节点,可以循环它们。

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

是的!非常感谢!这有助于太多......而这甚至不是我的问题! – krummens