Extract Xpaths of all nodes and then their attributes

前端 未结 1 837
南笙
南笙 2021-01-22 11:49

I am struggling with xslt from the past 2 days, owing to my starter status.My requirement is that given any input XML file ,I want the output to be a list of all the XPaths of a

相关标签:
1条回答
  • 2021-01-22 12:34

    I think there's a discrepancy between your sample input and output, in that the output describes a filter element with two conditions that's not in the source XML. At any rate, I believe this works:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="text" indent="no" />
      <!-- Handle attributes -->
      <xsl:template match="@*">
        <xsl:apply-templates select="ancestor-or-self::*" mode="buildPath" />
        <xsl:value-of select="concat('/@', name())"/>
        <xsl:text>&#xA;</xsl:text>
      </xsl:template>
    
      <!-- Handle non-leaf elements (just pass processing downwards) -->
      <xsl:template match="*[@* and *]">
        <xsl:apply-templates select="@* | *" />
      </xsl:template>
    
      <!-- Handle leaf elements -->
      <xsl:template match="*[not(*)]">
        <xsl:apply-templates select="ancestor-or-self::*" mode="buildPath" />
        <xsl:text>&#xA;</xsl:text>
        <xsl:apply-templates select="@*" />
      </xsl:template>
    
      <!-- Outputs a path segment for the matched element: '/' + name() + [ordinalPredicate > 1] -->
      <xsl:template match="*" mode="buildPath">
        <xsl:value-of select="concat('/', name())" />
        <xsl:variable name="sameNameSiblings" select="preceding-sibling::*[name() = name(current())]" />
        <xsl:if test="$sameNameSiblings">
          <xsl:value-of select="concat('[', count($sameNameSiblings) + 1, ']')" />
        </xsl:if>
      </xsl:template>
    
      <!-- Ignore text -->
      <xsl:template match="text()" />
    </xsl:stylesheet>
    
    0 讨论(0)
提交回复
热议问题