prime
prime

Reputation: 809

Add New tag if the tag does not exist

I have an input xml and I want to add new tags if the tags does not exist in xml.

<xsl:template match="jsonObject[not(aaa)]">
  <xsl:copy>
   <xsl:apply-templates select="@*"/>

     <aaa>test</aaa>
   <xsl:apply-templates select="node()"/>
  </xsl:copy>
    </xsl:template>

    <xsl:template match="jsonObject[not(bbb)]">
  <xsl:copy>
   <xsl:apply-templates select="@*"/>

     <bbb>test2</bbb>
   <xsl:apply-templates select="node()"/>
  </xsl:copy>
    </xsl:template>

Input message

<jsonObject>
   <ttt>xxxx</ttt>
   <ppp>yyy</ppp>
   <mmm>zzz</mmm>
   <ddd>00000</ddd>
<jsonObject>

expected message

<jsonObject>
   <aaa>test</aaa>
   <bbb>test2</bbb>
   <ttt>xxxx</ttt>
   <ppp>yyy</ppp>
   <mmm>zzz</mmm>
   <ddd>00000</ddd>
<jsonObject>

But, from the template, I implemented only the last tag has been added to the input message.

Received message

<jsonObject>
   <bbb>test2</bbb>
   <ttt>xxxx</ttt>
   <ppp>yyy</ppp>
   <mmm>zzz</mmm>
   <ddd>00000</ddd>
<jsonObject>

Is there any issue in my template?

Upvotes: 0

Views: 71

Answers (2)

Amrendra Kumar
Amrendra Kumar

Reputation: 1816

Complete XSLT is like:

<?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"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output indent="yes"/>

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

    <xsl:template match="jsonObject">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:if test="not(aaa)">
                <aaa>test</aaa>
            </xsl:if>
            <xsl:if test="not(bbb)">
                <bbb>test2</bbb>
            </xsl:if>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
    </xsl:template>


</xsl:stylesheet>

Upvotes: 1

Tim C
Tim C

Reputation: 70638

If you have a jsonObject that has neither an aaa nor bbb element, then both templates will match with equal priority, which is considered an error.

What you can do, is simply have a template matching all jsonObject elements and have xsl:if checks inside

<xsl:template match="jsonObject">
<xsl:copy>
  <xsl:apply-templates select="@*"/>
  <xsl:if test="not(aaa)">
     <aaa>test</aaa>
  </xsl:if>
  <xsl:if test="not(bbb)">
     <bbb>test2</bbb>
  </xsl:if>
  <xsl:apply-templates />
</xsl:copy>
</xsl:template>

Upvotes: 4

Related Questions