2011-12-07 73 views
2

如何删除子节点的父节点,但保留所有子节点?PHP domDocument删除子节点的子节点

XML文件是这样的:

<?xml version='1.0'?> 
<products> 
<product> 
<ItemId>531<ItemId> 
<modelNumber>00000</modelNumber> 
<categoryPath> 
<category><name>Category A</name></category> 
<category><name>Category B</name></category> 
<category><name>Category C</name></category> 
<category><name>Category D</name></category> 
<category><name>Category E</name></category> 
</categoryPath> 
</product> 
</products> 

基本上,我需要删除categoryPath节点和类别节点,但把所有的名字节点的产品节点的内部。我的目标是这样一个文件:

<?xml version='1.0'?> 
<products> 
<product> 
<ItemId>531<ItemId> 
<modelNumber>00000</modelNumber> 
<name>Category A</name> 
<name>Category B</name> 
<name>Category C</name> 
<name>Category D</name> 
<name>Category E</name> 
</product> 
</products> 

是否有PHP内置函数来做到这一点?任何指针将不胜感激,我只是不知道从哪里开始,因为有许多子节点。

感谢

回答

0

一个好的方法来处理XML数据是使用DOM设施。

一旦你介绍它就很容易。例如:

<?php 

// load up your XML 
$xml = new DOMDocument; 
$xml->load('input.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'); 

// 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(); 

See it in action

+0

非常感谢。我看到它只是删除所有其他类别标签。这是否应该发生? – Ben

+0

// @本:其实没有。给我第二个解决这个问题。 – Jon

+0

@Ben:固定的,我被一些......有趣的...... DOMNodeList的行为所吸引。请参阅[this](http://www.php.net/manual/en/domdocument.getelementsbytagname.php#99716)以了解发生的事情;你可以重写那个注释中的for来解决这个问题,但我更喜欢'while',因为它看起来很自然,即使你不知道发生了什么,以及为什么写这样一个'for'是必须的。 – Jon