Xpath: Select Direct Child Elements

25,189

Solution 1

Or even:

/*/*

this selects all element - children of the top element (in your case named parent) of the XML document.

XSLT - based verification:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
  <xsl:copy-of select="/*/*"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

<parent>
    <child1>
        <data1>some data</data1>
    </child1>
    <child2>
        <data2>some data</data2>
    </child2>
    <child3>
        <data3>some data</data3>
    </child3>
</parent>

the XPath expression is evaluated and the selected nodes are output:

<child1>
   <data1>some data</data1>
</child1>
<child2>
   <data2>some data</data2>
</child2>
<child3>
   <data3>some data</data3>
</child3>

Solution 2

This should select all child elements of <parent>

/parent/*

PHP Example

$xml = <<<_XML
<parent>
  <child1>
    <data1>some data</data1>
  </child1>
  <child2>
    <data2>some data</data2>
  </child2>
  <child3>
    <data3>some data</data3>
  </child3>
</parent>
_XML;

$doc = new DOMDocument();
$doc->loadXML($xml);

$xpath = new DOMXPath($doc);
$children = $xpath->query('/parent/*');
foreach ($children as $child) {
    echo $child->nodeName, PHP_EOL;
}

Produces

child1
child2
child3
Share:
25,189
Nic Hubbard
Author by

Nic Hubbard

Updated on July 24, 2022

Comments

  • Nic Hubbard
    Nic Hubbard almost 2 years

    I have an XML Document like the following:

    <parent>
    <child1>
      <data1>some data</data1>
    </child1>
    <child2>
      <data2>some data</data2>
    </child2>
    <child3>
      <data3>some data</data3>
    </child3>
    </parent>
    

    I would like to be able to get the direct children of parent (or the element I specify) so that I would have child1, child2 and child3 nodes.

    Possible?

  • Phil
    Phil over 12 years
    @NicHubbard Works for me using PHP's DOMDocument and DOMXpath. Is that your actual XML?
  • Nic Hubbard
    Nic Hubbard over 12 years
    No, that was just an example, but was the same idea I needed to solve.