Missmile03
Missmile03

Reputation: 21

XSLT filter XML documents that contains a specific letter

I am new in XLST and I have an assignment to do. I have to filtered a XML document so that only those elements whose names contain the letter "a" are included.

The result must contains the name of the element. By example:

If I have the following XML:

    <?xml-stylesheet href="monfichier.xsl" type="text/xsl" ?>
    <a>
    <ab x="x"><b>Test</b><a>z</a></ab>
    <z x="x"><a>z</a></z>
    </a>

The result must be:

   <a>
   <ab x="x"><a>z</a></ab>
   </a>

How can I do this? I try multiples ways to obtain the good result with name(.), the contains function but it doesn't work.

Can you help me please?

Upvotes: 0

Views: 395

Answers (1)

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

you can first start with an identity template:

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

then, an override template that eliminates other nodes that do not contain an a

<xsl:template match="*[not(contains(name(), 'a'))]"/>

thus the following stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes" omit-xml-declaration="yes"/>

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

    <xsl:template match="*[not(contains(name(), 'a'))]"/>

</xsl:stylesheet>

Upvotes: 1

Related Questions