Inder malviya
Inder malviya

Reputation: 141

Modify existing element of XML based on attribute value

I want to update the value in XML based on attribute value using XSLT below is the Input and Output XML

In this example, I want to append hard-coded value in the input string.

Input XML

<MyInfo isSurname="true">
    <name sysid="0">Google</name>
</MyInfo>

Output XML

<MyInfo isSurname="true" surname="Drive">
    <name sysid="0">Google Drive</name>
</MyInfo>

For every input name surname will be same. so when the attribute isSurname is true we need to add "Drive" as surname

Upvotes: 0

Views: 59

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 116993

This will work for your short example - not sure if those are the general rules you want to apply:

<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="@isSurname[.='true']">
    <xsl:copy/>
    <xsl:attribute name="surname">Drive</xsl:attribute>
</xsl:template>

<xsl:template match="name[../@isSurname='true']/text()">
    <xsl:copy/>
    <xsl:text> Drive</xsl:text>
</xsl:template>

</xsl:stylesheet>   

Upvotes: 0

Vebbie
Vebbie

Reputation: 1695

Let's put your Input XML in a root node as below:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
   <MyInfo isSurname="true">
       <name sysid="0">Google</name>
   </MyInfo>
</Root>

The solution in XSLT 1.0, can be:

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

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

<xsl:template match="/Root/MyInfo">
    <xsl:choose>
        <xsl:when test="@isSurname = 'true'">
            <xsl:copy>
                <xsl:attribute name="surname">
                    <xsl:value-of select="'Drive'" />
                </xsl:attribute>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="/Root/MyInfo[@isSurname = 'true']/name/text()">
    <xsl:value-of select="concat(.,' Drive')" />
</xsl:template>

There's a check based on the isSurname attribute.

  • If it is true, then the Output XML given by you will be populated.
  • If it is false, then the Input XML will be displayed as it is.

Upvotes: 1

Related Questions