Psytronic
Psytronic

Reputation: 6113

XPath select certain amount of levels only

If I have an xml structure like this

<root>
  <sub>
    <node />
    <node />
  </sub>
    <sub>
      <node />
    <sub>
  <sub>
    <sub>
      <node />
    </sub>
  </sub>
  <sub>
    <sub>
      <sub>
        <node />
      </sub>
      <node />
    </sub>
  </sub>
  <node />
  <node />
</root>

Is there an xpath syntax which will only select the first three levels of nodes?

so it will collect

<root>
  <sub>
    <node />
    <node />
  </sub>
    <sub />
  <sub>
    <sub />
  </sub>
  <sub>
    <sub />
  </sub>
  <node />
  <node />
</root>

UPDATE

Just to explain what I'm doing, I've got an asp:treeview, which I am binding to an asp:xmldatasource, and I want the tree view to only go three nodes deep. It may be possible to do it on the treeview or xmldatasource control another way, but the xpath seemed the most obvious

Thanks, Psy

Upvotes: 1

Views: 3177

Answers (2)

Lucero
Lucero

Reputation: 60246

You can check the ancestor axis count, which is in fact the depth:

//*[count(ancestor::*)<3]

Upvotes: 8

topskip
topskip

Reputation: 17355

You can add a rule that matches everything below a certain level that "does nothing":

<xsl:template match="/*/*/*/*"/>

So a complete example:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output indent="yes"/>
  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>


  <xsl:template match="/*/*/*/*"/>

</xsl:stylesheet>

Upvotes: 1

Related Questions