2011-12-07 72 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