title: Manipulate child elements with xPath in PHP
body: <p>I have a XML document with an element (named <code>region</code>) that may or may not have multiple child elements. For my import i need to make sure that there is only one child element. If there are more child elements, i need to remove all children, except the last one. The following situations can occur:</p>
  
  <pre><code> // Option 1: No child elements
   &lt;property name="region"&gt;
   &lt;/property&gt;
  
   // Option 2: One child element
   &lt;property name="region"&gt;
   &lt;value&gt;Bottom&lt;/value&gt;
   &lt;/property&gt;
  
   // Option 3: Two child elements
   &lt;property name="region"&gt;
   &lt;value&gt;Top&lt;/value&gt;
   &lt;value&gt;Bottom&lt;/value&gt;
   &lt;/property&gt;
  
   // Option 4: Three child elements
   &lt;property name="region"&gt;
   &lt;value&gt;Top&lt;/value&gt;
   &lt;value&gt;Middle&lt;/value&gt;
   &lt;value&gt;Bottom&lt;/value&gt;
   &lt;/property&gt;
  </code></pre>
  
  <p>What i need is to filter the XML to re-format the child elements of the <code>region</code> element to always have one child element (<code>value</code>) with ether the last child element's value or if there are no children, the value 'none'.</p>
  
  <p>My desired output would be the following:</p>
  
  <pre><code> // For Option 1
   &lt;property name="region"&gt;
   &lt;value&gt;none&lt;/value&gt;
   &lt;/property&gt;
  
   // For option 2, 3 &amp; 4
   &lt;property name="region"&gt;
   &lt;value&gt;Bottom&lt;/value&gt;
   &lt;/property&gt;
  </code></pre>
  
  <p>I know i can select the <code>region</code> property with the xPath query <code>//property[@name = "region"]</code>, but i don't know how to manipulate the children from there. </p>
  
  <p>I have the following code when i get stuck</p>
  
  <pre><code> &lt;?php
   $xml = '&lt;properties&gt;
        &lt;property name="region"&gt;
        &lt;/property&gt;
  
        &lt;property name="region"&gt;
        &lt;value&gt;Bottom&lt;/value&gt;
        &lt;/property&gt;
  
        &lt;property name="region"&gt;
        &lt;value&gt;Top&lt;/value&gt;
        &lt;value&gt;Bottom&lt;/value&gt;
        &lt;/property&gt;
  
        &lt;property name="region"&gt;
        &lt;value&gt;Top&lt;/value&gt;
        &lt;value&gt;Middle&lt;/value&gt;
        &lt;value&gt;Bottom&lt;/value&gt;
        &lt;/property&gt;
   &lt;/properties&gt;';
   $document = new DOMDocument();
   $document-&gt;loadXML($xml);
   $xpath = new DOMXpath($document);
   foreach($xpath-&gt;query('//property[@name = "region"]') as $node){
  
        // Now i need something like below, but i can't find a way to make it work
        if $node-&gt;hasChildren()
             Remove all but last child
        else
             Create child element with text none
   }
  </code></pre>
  
  <p>I hope somebody can point me in the right direction</p>