1
votes

How can I, with XSLT, select nodes based on a substring of the nodes' element name?

For example, consider the XML:

<foo_bar>Keep this.
  <foo_who>Keep this, too.
    <fu_bar>Don't want this.</fu_bar>
  </foo_who>
</foo_bar>

From which I want to output:

<foo_bar>Keep this.
  <foo_who>Keep this, too.
  </foo_who>
</foo_bar>

Here I want to select for processing those nodes whose names match a regex like "foo.*".

I think I need an XSLT template match attribute expression, or an apply-templates select attribute expression, that applies the regex to the element's name. But maybe this can't be done without some construct like an statement?

Any help would be appreciated.

1

1 Answers

2
votes

Here is some XSL that finds elements that start with "foo" to get you started. I don't think regex functionality was added until XSLT 2.0 based on Regular Expression Matching in XSLT 2.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="*">
        <xsl:variable name="name" select="local-name()"/>
        <xsl:if test="starts-with($name, 'foo')">
            <xsl:copy>
                <xsl:apply-templates/>
            </xsl:copy>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

It gives this output, which seems to have an extra newline.

<foo_bar>Keep this.
  <foo_who>Keep this, too.

  </foo_who>
</foo_bar>