Nic Hubbard
Nic Hubbard

Reputation: 42175

Xpath: Select Direct Child Elements

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?

Upvotes: 8

Views: 26271

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243569

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>

Upvotes: 12

Phil
Phil

Reputation: 164952

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

Upvotes: 6

Related Questions