【问题标题】:PHP domDocument to remove child nodes of a child nodePHP domDocument 删除子节点的子节点
【发布时间】:2013-11-09 15:48:04
【问题描述】:

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

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 内置函数来执行此操作?任何指针都将不胜感激,我只是不知道从哪里开始,因为有很多子节点。

谢谢

【问题讨论】:

    标签: php xml dom document


    【解决方案1】:

    处理 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.

    【讨论】:

    • 非常感谢。我看到它只是删除了所有其他类别标签。这应该发生吗?
    • @Ben:实际上,没有。给我一点时间来解决这个问题。
    • @Ben: 修正,我被DOMNodeList 的一些……有趣的……行为抓住了。请参阅this 了解所发生的情况;您可以按照该评论中的指示重写for 以解决问题,但我更喜欢while,因为即使您不知道发生了什么以及为什么写for 的方式如此奇怪,它看起来也很自然是必需的。
    • 哦,好的。我阅读了 php.net 上的文档。伟大的。要删除 categoryPath,我可以使用您编写的代码的某些部分,对吗?如果我使用 getElementsByTagName 然后使用 removeChild,它会起作用吗?
    • @Ben:代码应该是可重用的 :) 虽然我不确定你建议做什么。但我想你明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多