简体   繁体   English

PHP domDocument删除子节点的子节点

[英]PHP domDocument to remove child nodes of a child node

How do I remove a parent node of a child node, but keep all the children? 如何删除子节点的父节点,但保留所有子节点?

The XML file is this: 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>

Basically, I need to remove the categoryPath node and the category node, but keep all of the name nodes inside of the product node. 基本上,我需要删除categoryPath节点和category节点,但将所有名称节点保留在product节点内。 What I am aiming for is a document like this: 我想要的是一个像这样的文件:

 <?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>

Is there PHP built in function to do this? 有内置的PHP函数可以做到这一点吗? Any pointers would be appreciated, I just do not know where to start because there are many child nodes. 任何指针将不胜感激,我只是不知道从哪里开始,因为有许多子节点。

Thanks 谢谢

A good approach to process XML data is to use the DOM facility. 处理XML数据的一种好方法是使用DOM工具。

It's quite easy once you get introduced to it. 一经介绍就非常容易。 For example: 例如:

<?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 . 看到它在行动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM