tags:

views:

64

answers:

2

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

+1  A: 

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>
Patrick
Creating this as an xsl file, and then assigning it to the TransformFile property on the xmldatasource control works. Brilliant idea! Thanks
Psytronic
there should be an xpath function that returns the depth of the context node
vtd-xml-author
+1  A: 

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

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