2011-12-07 144 views
1

我使用此代码: 我试图删除categoryPath节点但保留子节点(所有名称标签) 它目前离开categoryPath,但我在寻找建议至于我如何删除categoryPath节点,但保留子节点。php删除子节点但保留它的子节点

<?php 

// load up your XML 
$xml = new DOMDocument; 
$xml->load('book.xml'); 

// Find all elements you want to replace. Since your data is really simple, 
// you can do this without much ado. Otherwise you could read up on XPath. 
// See http://www.php.net/manual/en/class.domxpath.php 
$elements = $xml->getElementsByTagName('category'); 
$categoryPath = $xml->getElementsByTagName('categoryPath'); 
// WARNING: $elements is a "live" list -- it's going to reflect the structure 
// of the document even as we are modifying it! For this reason, it's 
// important to write the loop in a way that makes it work correctly in the 
// presence of such "live updates". 


while($elements->length) { 
$category = $elements->item(0); 
$name = $category->firstChild; // implied by the structure of your XML 

// replace the category with just the name 
$category->parentNode->replaceChild($name, $category); 

}

// final result: 
$result = $xml->saveXML(); 
echo $result; 
?> 

但它不会删除categoryPath节点

的XML:

<?xml version="1.0"?> 
<products> 
<product> 
<bestBuyItemId>531670</bestBuyItemId> 
<modelNumber>METRA ELECTRONICS/MOBILE AUDIO</modelNumber> 
<categoryPath> 
<name>ddd</name> 
<name>Car, Marine &amp; GPS</name> 
<name>Car Installation Parts</name> 
<name>Deck Installation Parts</name> 
<name>Antennas &amp; Adapters</name> 
</categoryPath> 
</product> 

</products> 

回答

1

你必须在下面的行了一个问题:

$elements = $xml->getElementsByTagName('category'); 

什么节点应该是类别?我没有在你的xml文件中看到任何类别节点。

然后,此代码:

while($elements->length) { 
    $category = $elements->item(0); 
    $name = $category->firstChild; // implied by the structure of your XML 

    // replace the category with just the name 
    $category->parentNode->replaceChild($name, $category); 
} 

不能肯定,因为$elements是空的工作。

你想要的是选择所有的name节点,然后将它们附加到product节点。例如:

+0

这是我删除的节点。 – Ben

+0

已经更新的答案。 –

+0

你能给我一个如何做到这一点的想法吗? – Ben