0

I'm trying to build up a XSLT logic where I can replace a value considering its actual value.

I have the following XML:

<?xml version="1.0" encoding="UTF-8"?>
  <DOC BEGIN="1">
    <BESKZ>X</BESKZ>
    <NUM1>1010</NUM1>
    <NAME>ABC</NAME>
  </DOC>

Now I want to apply the following logic in XSLT version 1:

IF value of BESKZ is "X" replace value with "NS_CFS"
ELIF value of BESKZ is "E" replace value with "INV_CFS"
ELIF value of BESZK is anything else do noting

and

IF value of NAME is set to anything (not null) replace value with "SERIAL"

So THE Upper example should be this output:

<?xml version="1.0" encoding="UTF-8"?>
  <DOC BEGIN="1">
    <BESKZ>NS_CFS</BESKZ>
    <NUM1>1010</NUM1>
    <NAME>SERIAL</NAME>
  </DOC>

I'm very new in xslt, can anyone help me?

nicow
  • 11
  • 2

1 Answers1

1

It's typical in XSLT to approach problems like this using a set of independent templates, each of which matches one of the cases you want to deal with. Combine these templates with an "identity template" that simply copies things unchanged, and you have a solution. e.g.

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

  <!-- identity template copies any node which isn't handled by a more specific template -->
  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

  <!-- templates for handling specific cases -->
  
  <!-- IF value of BESKZ is "X" replace value with "NS_CFS" -->
  <xsl:template match="BESKZ/text()[.='X']">NS_CFS</xsl:template>
  
  <!-- ELIF value of BESKZ is "E" replace value with "INV_CFS" -->
  <xsl:template match="BESKZ/text()[.='E']">INV_CFS</xsl:template>
  
  <!-- IF value of NAME is set to anything (not null) replace value with "SERIAL" -->
  <xsl:template match="NAME/text()">SERIAL</xsl:template>
  
</xsl:stylesheet>

These templates match the text nodes contained within certain elements (that's what the expression text() matches), so they don't need to create or copy element nodes; they just need to produce a new text node to replace the one they matched.

Note that the specific templates will match those text nodes, even though the generic template would also match them; that's because the specific templates have a higher "priority" than the generic template does. The priority of a template can be set explicitly using the priority attribute of a template, but generally you don't need to do this because if you don't set an explicit priority it's calculated by the XSLT processor based on a template's select expression: basically more complex select expressions will yield higher priorities. See section 5.5 Conflict Resolution for Template Rules of the XSLT for details.

Conal Tuohy
  • 2,561
  • 1
  • 8
  • 15