pgoose231989
pgoose231989

Reputation: 23

XSLT create new tag if exists else update tag if exists

Is there a way for me to update the label element to Selma if "LastName" exists and if the label LastName doesn't exist then add the "LastName" and "label" elements to the XML?

<xml>
   <udfs>
      <udf>
         <desc>FirstName</desc>
         <label>Sam</label>
      </udf>
   
   <udf>
         <desc>LastName</desc>
         <label>Selman</label>
      </udf>
   </udfs>
</xml>

Here's what I have right now:

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

    <xsl:template match="udf[desc='LastName']/fieldValue">
        <xsl:value-of select="'Selma'"/>
    </xsl:template>  

    <xsl:template match="udf[not(desc='LastName')]">
        <desc>LastName</desc>
        <label>Selma</label>
    </xsl:template> 
</xsl:stylesheet>

Upvotes: 1

Views: 178

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117102

I think you want to do:

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="udf[desc='LastName']/label">
    <label>Selma</label>
</xsl:template>  

<xsl:template match="udfs[not(udf/desc='LastName')]">
    <xsl:copy>
        <xsl:apply-templates/>
        <udf>
            <desc>LastName</desc>
            <label>Selma</label>
        </udf>
    </xsl:copy>
</xsl:template> 
 
</xsl:stylesheet>

Upvotes: 1

Related Questions