[SOLVED] XPath How to select only one depth of children element

Issue

Suppose I have this XML file:

<root xmlns:foo="" xmlns:bar="">
    <actors>
        <actor id="1">Christian Bale</actor>
        <actor id="2">Liam Neeson</actor>
        <actor id="3">Michael Caine</actor>
    </actors>
    <foo:singers>
        <foo:singer id="4">Tom Waits</foo:singer>
        <foo:singer id="5">B.B. King</foo:singer>
        <foo:singer id="6">Ray Charles</foo:singer>
    </foo:singers>
</root>

How do I use XPath to get

<actors> </actors>
<foo:singers> </foo:singers>

If I use /root/* to query the XML file, it will give me the result

<actors>
    <actor id="1">Christian Bale</actor>
    <actor id="2">Liam Neeson</actor>
    <actor id="3">Michael Caine</actor>
</actors>

and

<foo:singers>
    <foo:singer id="4">Tom Waits</foo:singer>
    <foo:singer id="5">B.B. King</foo:singer>
    <foo:singer id="6">Ray Charles</foo:singer>
</foo:singers>

I don’t want the grandchildren of the <root></root>. I only need the first descendent.

Solution

Your query yields only 2 results indeed, the actors and the foo:singers element. If you display the results, however, the elements will be shown with all their children (which may have children again, and so forth).

If your query processor supports XQuery, you can modify the resulting nodes and replace the resulting nodes with new elements:

/root/*/(element { node-name(.) } { @* })

If you want to suppress the output of attributes, you can additionally get rid of the nested @* path.

Answered By – Christian Grün

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.