Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the shallowest matching elements with XPath?

Let's say I have this document.

<a:Root>
    <a:A>
        <title><a:B/></title>
        <a:C>
            <item><a:D/></item>
        </a:C>
    </a:A>
</a:Root>

And I have an XmlNode set to the <a:A> element.

If I say

A.SelectNodes( "//a:*", namespaceManager )

I get B, C, and D. But I don't want D because it's nested in another "a:" element.

If I say

A.SelectNodes( "//a:*[not(ancestor::a:*)]", namespaceManager )

of course, I get nothing, since both A and its parent are in the "a" namespace.

How can I select just B and C, that is, the shallowest children matching the namespace?

Thanks.

Note, this is XPath 1.0 (.NET 2), so I can't use in-scope-prefixes (which it appears would help).

Also, this isn't really a question about namespaces. The quandary would be the same with other matching criteria.

like image 447
harpo Avatar asked Nov 21 '25 18:11

harpo


2 Answers

What about this:

<xsl:variable name="parents" select="ancestor-or-self::a:*" />
<xsl:value-of select="//a:*[not(deep-equal(ancestor::a:*, $parent))]" />

In XSLT this seems simple to do (store a node set as a variable), but I don't exactly know how to implement this in C#.

Edit: Working further on the idea of using count, this can probably work:

int nrParents = A.SelectNodes("ancestor-or-self::a:*", namespaceManager).Count(); // Or was it Size?
A.SelectNodes("//a:*[count(ancestor::a:*)!=" + nrParents + "]", namespaceManager)
like image 133
Marc Avatar answered Nov 23 '25 06:11

Marc


This is not an XSLT question, so here is a single XPath expression that selects the two nodes wanted:

/*/*/descendant::a:*[not(count(ancestor::a:*) > 2)]
like image 43
Dimitre Novatchev Avatar answered Nov 23 '25 06:11

Dimitre Novatchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!