JRQ
JRQ

Reputation: 545

Simple XSLT where the IF test is failing

I have a simple XML document that I'm trying to replace an element based on the element's value.

<document>
<meta>
    <wk_abc>
        UCM:SOURCE1
    </wk_abc>
    <wk_def>
        Other Text
    </wk_def>
    <wk_abc>
        UCM:SOURCE2
    </wk_abc>
</meta>
<content>
    Lorem ipsum
</content>
</document>

My XSL is this:

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

<xsl:template match="wk_abc">
   <xsl:if test=".='UCM:SOURCE1'">
        <bob>bob</bob>
    </xsl:if>
</xsl:template>

But it keeps failing the IF condition. and skipping over the replacement element. Why is this test failing?

Upvotes: 1

Views: 362

Answers (3)

It looks like a whitespace issue. If I change your input file to <document> <meta> <wk_abc>UCM:SOURCE1</wk_abc> <wk_def> Other Text </wk_def> <wk_abc> UCM:SOURCE2 </wk_abc> </meta> <content> Lorem ipsum </content> </document>

If the input document had spaces they are preserved. If you want further control of spaces processing use, xsl-strip construct. Look at the articles below on how to granularly control whitespace processing: http://www.ibm.com/developerworks/library/x-tipwhitesp/

There are some earlier suggestions in stackoverflow on how to use these constructs: Whitespace node in XSLT

You may also try normalize-space as suggested in: How to Trim in xslt?

From the XSLT spec(http://www.w3.org/TR/xslt#strip):

After the tree for a source document or stylesheet document has been constructed, but before it is otherwise processed by XSLT, some text nodes are stripped. A text node is never stripped unless it contains only whitespace characters. Stripping the text node removes the text node from the tree. The stripping process takes as input a set of element names for which whitespace must be preserved. The stripping process is applied to both stylesheets and source documents, but the set of whitespace-preserving element names is determined differently for stylesheets and for source documents.

Upvotes: 0

ptha
ptha

Reputation: 916

You could just use contains() for example:

<xsl:if test="contains(., 'UCM:SOURCE1')">

Upvotes: 0

Tim C
Tim C

Reputation: 70648

This is because there is whitespace either side of 'UCM:SOURCE1' in the node.

Try changing your xsl:if condition to this to remove the white-space before doing the check:

  <xsl:if test="normalize-space()='UCM:SOURCE1'">

Note that this does more than just trim the white space. If the text was UCM:SOURCE1 UCMSOURCE2 for example, the whitepsaces in the middle would be merged into one single space, so normalize-space would return UCM:SOURCE1 UCMSOURCE2

Upvotes: 2

Related Questions