Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath: Select Direct Child Elements

Tags:

xml

xpath

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?

like image 864
Nic Hubbard Avatar asked Jan 24 '12 01:01

Nic Hubbard


2 Answers

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>
like image 152
Dimitre Novatchev Avatar answered Oct 16 '22 07:10

Dimitre Novatchev


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
like image 26
Phil Avatar answered Oct 16 '22 06:10

Phil