user1326379
user1326379

Reputation: 170

xslt to Replace an xml attribute with another and a value with some other

I have an xml in following form:

<?xml version="1.0" encoding="UTF-8"?>
<query>
    <queryParams name="accountID">Star TV</queryParams>
    <queryParams name="assetID">Friends</queryParams>
    <queryParams name="accountExtRef">Tata</queryParams>
</query>

I need separate xslt to:

  1. replace name="providerID" with name="ContentProvider" such that the resulting xml becomes:

    <?xml version="1.0" encoding="UTF-8"?>
    <query>
        <queryParams name="companyID">Star TV</queryParams>
        <queryParams name="assetID">Friends</queryParams>
        <queryParams name="accountExtRef">Tata</queryParams>
    </query>
    
  2. replace "Star TV" with Colors such that the XML becomes

        <?xml version="1.0" encoding="UTF-8"?>
        <query>
            <queryParams name="accountID">Colors</queryParams>
            <queryParams name="assetID">Friends</queryParams>
            <queryParams name="accountExtRef">Tata</queryParams>
        </query>
    

Please help.

Upvotes: 1

Views: 454

Answers (1)

Tim C
Tim C

Reputation: 70618

You could do this by simply adding extra templates to the identity transform to match the changes you need.

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

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

   <xsl:template match="queryParams/@name[. = 'accountID']">
      <xsl:attribute name="name">companyID</xsl:attribute>
   </xsl:template>

   <xsl:template match="queryParams/text()[. = 'Star TV']">
      <xsl:text>Colors</xsl:text>
   </xsl:template>
</xsl:stylesheet>

When applied to your sample XML, the following is output

<query>
   <queryParams name="companyID">Colors</queryParams>
   <queryParams name="assetID">Friends</queryParams>
   <queryParams name="accountExtRef">Tata</queryParams>
</query>

In this case, it does both changes in one go, but it should be clear enough how to split this into two separate XSLTs if required.

Upvotes: 1

Related Questions