如何删除子节点的父节点,但保留所有子节点?
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 :(得分: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 强>