tsjo
tsjo

Reputation: 3

Duplicate a node and child elements if it occurs only once

I need to duplicate a node and its child elements, if it occurs only once in the xml. Otherwise, the xml shouldn't be modified. For ex, in the below xml, if <dataList> occurs only once then duplicate it one more time. If not, don't change the xml at all. Only XSLT 1.0 please.

Input XML

 <?xml version="1.0" encoding="UTF-8"?>
<API>
   <Token/>
   <root>
     <dataList>
        <addressOne>1</addressOne>
        <addressTwo/>
        <bkdn/>
     </dataList>
   </root>
 </API>

Expected output xml

<?xml version="1.0" encoding="UTF-8"?>
 <API>
   <Token/>
   <root>
      <dataList>
         <addressOne>1</addressOne>
         <addressTwo/>
         <bkdn/>
      </dataList>
      <dataList>
         <addressOne>1</addressOne>
         <addressTwo/>
         <bkdn/>
       </dataList>
     </root>
</API>

Upvotes: 0

Views: 60

Answers (1)

Amrendra Kumar
Amrendra Kumar

Reputation: 1816

As per my understanding here i want to solve it:

<?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="1.0">

    <xsl:output indent="yes"/>

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

    <xsl:template match="root">
        <xsl:copy>

        <xsl:choose>

            <!-- If you are looking for the dataList occurance then use count -->
            <xsl:when test="count(dataList) = 1">

            <!-- If you are looking for the dataList/addressOne value = 1 occurance then use below -->

        <!-- <xsl:when test="dataList/addressOne=1"> -->
                <xsl:apply-templates select="dataList"/>
                <xsl:apply-templates select="dataList"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates select="dataList"/>
            </xsl:otherwise>
        </xsl:choose>
        </xsl:copy>
    </xsl:template>



</xsl:stylesheet>

Upvotes: 0

Related Questions