user3882500
user3882500

Reputation: 5

Finding a XML element with a variable/changing location using XSLT

Using XSLT, I need to locate the tag element from an XML file to start doing the wanted transformations. The tag element is typically the root element.

<tag>
   ...
</tag>

However, a new collection of XML files arrived and some of them have the tag element somewhere else. (its location vary from file to file)

<a>
  <b>
    <tag>
      ...
    </tag>
  </b>
</a>

I would like to know if its possible to obtain the full path/name of tag and store it into a variable, so I could use $tagPath instead of /a/b/tag. I tried using the name() function but it only returns the element name (tag).

Thanks!

Upvotes: 0

Views: 380

Answers (1)

JohnLBevan
JohnLBevan

Reputation: 24470

Per the comments above, to find the tag element regardless of position, you can just use \\tag.

If you need the full path of this element, you can use the solution proposed here: How do you output the current element path in XSLT?.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="text()|@*">
      <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
      </xsl:copy>
  </xsl:template>

  <xsl:template match="//tag">
      <xsl:call-template name="genPath" />
  </xsl:template>

  <xsl:template name="genPath">
      <xsl:param name="prevPath" />
      <xsl:variable name="currPath" select="concat('/',name(),'[',count(preceding-sibling::*[name() = name(current())])+1,']',$prevPath)" />
      <xsl:for-each select="parent::*">
        <xsl:call-template name="genPath">
          <xsl:with-param name="prevPath" select="$currPath" />
        </xsl:call-template>
      </xsl:for-each>
      <xsl:if test="not(parent::*)">
        <xsl:value-of select="$currPath" />      
      </xsl:if>
  </xsl:template>

</xsl:stylesheet>

You can see an example of this here: http://fiddle.frameless.io/

Upvotes: 1

Related Questions