php删除子节点但保留其子节点

时间:2011-12-07 02:58:52

标签: php xml

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

<?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 个答案:

答案 0 :(得分: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节点。类似的东西:

foreach ( $xml->getElementsByTagName('product') as $product ) {
    foreach( $product->getElementsByTagName('name') as $name ) {
        $product->appendChild( $name );
    }
    $product.removeChild( $xml->getElementsByTagName('categoryPath')->item(0) );
}