Srikanth Reddy
Srikanth Reddy

Reputation: 89

XSLT 1.0 - how to check when condition for string

I am trying to conditional check on the input xml file and place the value.

input xml:

<workorder>
    <newwo>1</newwo>
</workorder>

If newwo is 1, then I have to set in my output as "NEW" else "OLD"

Expected output is:

newwo: "NEW"

my xslt is:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:xs="http://www.w3.org/2001/XMLSchema"  version="2.0">

<xsl:template match="/">

        <xsl:apply-templates select="NEWWO" />

</xsl:template>
<xsl:template match="/NEWWO">
    <xsl:text>{
      newwo:"
    </xsl:text>
        <xsl:choose>
            <xsl:when test="NEWWO != '0'">NEW</xsl:when>
            <xsl:otherwise>OLD</xsl:otherwise>
        </xsl:choose>
    <xsl:text>"
    }</xsl:text>
</xsl:template>

Please help me. Thanks in advance!

Upvotes: 1

Views: 2032

Answers (2)

Daniel Haley
Daniel Haley

Reputation: 52888

I see a number of reasons you aren't getting output.

  1. The xpaths are case sensitive. NEWWO is not going to match newwo.
  2. You match / and then apply-templates to newwo (case fixed), but newwo doesn't exist at that context. You'll either have to add */ or workorder/ to the apply-templates (like select="*/newwo") or change / to /* or /workorder in the match.
  3. You match /newwo (case fixed again), but newwo is not the root element. Remove the /.
  4. You do the following test: test="newwo != '0'", but newwo is already the current context. Use . or normalize-space() instead. (If you use normalize-space(), be sure to test against a string. (Quote the 1.))

Here's an updated example.

XML Input

<workorder>
    <newwo>1</newwo>
</workorder>

XSLT 1.0

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

  <xsl:template match="/*">
    <xsl:apply-templates select="newwo" />
  </xsl:template>

  <xsl:template match="newwo">
    <xsl:text>{&#xA;newwo: "</xsl:text>
    <xsl:choose>
      <xsl:when test=".=1">NEW</xsl:when>
      <xsl:otherwise>OLD</xsl:otherwise>
    </xsl:choose>
    <xsl:text>"&#xA;}</xsl:text>
  </xsl:template>

</xsl:stylesheet>

Output

{
newwo: "NEW"
}

Upvotes: 2

Rama Krishnam
Rama Krishnam

Reputation: 73

You try it as below

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

 <xsl:template match="/">
  <xsl:choose>
    <xsl:when test="/workorder/newwo = 1">
     <xsl:text disable-output-escaping="no"> newwo:New</xsl:text>
</xsl:when>
    <xsl:otherwise>
 <xsl:text disable-output-escaping="no"> newwo:Old</xsl:text>                    </xsl:otherwise>
  </xsl:choose>
  </xsl:template>
  </xsl:stylesheet>

Upvotes: 0

Related Questions