开发者

How to move childnode to parentnode level in xml ?

Recently I have been working with the xml coding,and the problem happened.

Given the xml like this:

<Colonel id="1">
  <Lieutenant_Colonel id="2">
    <Secretary id="6"/>
  </Lieutenant_Colonel>
  <Lieutenant_Colonel id="3">
    <Secretary id="7"/>
  </Lieut开发者_高级运维enant_Colonel>
  <Secretary id="5"/>
</Colonel>

now the Colonel(id=1) has gone with the Secretary(id=5)

the xml we want is like

<!-- <Colonel id="1"> -->
  <Lieutenant_Colonel id="2">
    <Secretary id="6"/>
  </Lieutenant_Colonel>
  <Lieutenant_Colonel id="3">
    <Secretary id="7"/>
  </Lieutenant_Colonel>
  <!--
  <Secretary id="5"/>
</Colonel> -->

or

<Lieutenant_Colonel id="2">
  <Secretary id="6"/>
</Lieutenant_Colonel>
<Lieutenant_Colonel id="3">
  <Secretary id="7"/>
</Lieutenant_Colonel>

How to do this work?

please help me


This is a pretty long them, so I´ll have to refer other questions. First, consider this function:

function RemoveColonel($id, $secretaryId)
{
    $colXpath = '//colonel[@id="' . $id . '"]';
    $secXpath = $colXpath . '/Secretary[@id="' . $secretaryId . '"]';

    RemoveNode($secXpath);
    $colChildren = $rootXml->xpath($colXpath)->children();
    $children = array();

    foreach ($colChildren as $child ){
        $children[] = $child;
    }

    RemoveNode($colXpath);
    return $children;
}

Given the Id of a colonel and a secretary for that colonel, it deletes the secretary, then it saves the colonel's children to remove the colonel and return the children. After that, you can insert your elements in the root node again if you please. If you can't have the secretary Id at the moment of deleting the colonel, you can workaround the xpath to remove the secretary as child of the colonel by removing the id specification.

The RemoveNode code is a bit long, so I'll have to give you this question on how to remove nodes using SimpleXML in PHP.

I hope I can be of some help!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜