L.Kate
L.Kate

Reputation: 17

How to Skip tags with characters like colon( : ) etc in XML using XSLT.?

I'm using XSLT 1.0 to transform the input XML to the desired output but failing in doing so.The XSlt code should skip the tags with ":". Please help me here.

I have an input XML :-

<Request name="BXML">
    <first>10</first>
    <second>20</second>
    <third>:</third>
    <fourth>:::</fourth>
</Request>

I want the output XML like this:-

<Request name="BXML">
    <first>10</first>
    <second>20</second>
</Request>

Upvotes: 0

Views: 372

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117018

To remove any element that contains a colon:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

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

</xsl:stylesheet>

To remove any element that contains only colons:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="*[not(translate(., ':', ''))]"/>

</xsl:stylesheet>

Upvotes: 0

Vebbie
Vebbie

Reputation: 1695

You can use translate to achieve the same as below:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="no" indent="yes" />
<xsl:strip-space elements="*" />

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

<xsl:template match="Request">
    <Request>
        <xsl:apply-templates select="@*" />
        <xsl:for-each select="*">
            <xsl:if test="translate(., ':', '') != ''">
                <xsl:copy>
                    <xsl:apply-templates />
                </xsl:copy>
            </xsl:if>
        </xsl:for-each>
    </Request>
</xsl:template>

</xsl:stylesheet>

http://xsltfiddle.liberty-development.net/gWvjQfC

Note: The translate function replaces individual characters of a string with other individual characters. So, here in this case translate() will replace each ':' (colon) character with '' (blank) character, and checks if the tag still contains text or it is empty. Based on that it will populate tags.

Upvotes: -1

Related Questions