[ create a new paste ] login | about

Link: http://codepad.org/1kUWgSaq    [ raw code | output | fork ]

PHP, pasted on Feb 25:
<?php

$xml = <<< XML
<nodes>    
<node1 name="aaa">
          <subnode   name="123456" />
          <subnode   name="92328" />
          <subnode   name="39576" />
    </node1>
    <node1  name="bbb">
          <subnode   name="28472" />
    </node1>
    <node1  name="ccc">
          <subnode   name="53554" />
          <subnode   name="01928" />
     </node1>
    <node1  name="ddd">
          <subnode   name="66666" />
    </node1>
</nodes>
XML;

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
// iterate all the subnodes
foreach ($xpath->query('/nodes/node1/subnode') as $subnode) {
    // get the subnodes parent node's name attribute
    $name = $subnode->parentNode->getAttribute('name');
    // fetch the first node element with that name attribute
    $node = $xpath->query("/nodes/node1[@name='$name']")->item(0);
    // move the subnode there
    $node->appendChild($subnode);
}
// iterate over all node1 elements that are now empty
foreach($xpath->query('/nodes/node1[not(*)]') as $node) {
    // remove them
    $node->parentNode->removeChild($node);
}
// print new dom tree
$dom->formatOutput = true;
echo $dom->saveXML();


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0"?>
<nodes>
  <node1 name="aaa">
    <subnode name="123456"/>
    <subnode name="92328"/>
    <subnode name="39576"/>
  </node1>
  <node1 name="bbb">
    <subnode name="28472"/>
  </node1>
  <node1 name="ccc">
    <subnode name="53554"/>
    <subnode name="01928"/>
  </node1>
  <node1 name="ddd">
    <subnode name="66666"/>
  </node1>
</nodes>


Create a new paste based on this one


Comments: