简体   繁体   中英

How to loop through any XML and replace a specific Value using XSLT

I want to create a XSLT Transformation which loops through any XML Structure and replaces a specific value. For example:

Input XML:

<?xml version="1.0" encoding="UTF-8"?>
<Node1>
    <Node2>
        <Node3>
            <Tag1>1</Tag1>
            <Tag2>2</Tag2>
            <Tag3>3</Tag3>
        </Node3>
    </Node2>
</Node1>

Let´s say I want to replace any Value "2" with "1"

Expected Output XML:

<?xml version="1.0" encoding="UTF-8"?>
<Node1>
    <Node2>
        <Node3>
            <Tag1>1</Tag1>
            <Tag2>1</Tag2>
            <Tag3>3</Tag3>
        </Node3>
    </Node2>
</Node1>

I already tried to loop with the xsl:for-each and xsl:if Statements, but it doesn´t work:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template  match="/"> 
        <xsl:copy-of select=".">
            <xsl:for-each select=".">
                <xsl:if test="xsl:value-of select = '2'">
                    xsl:value-of select = '1'
                </xsl:if>
            </xsl:for-each>
        </xsl:copy-of> 
    </xsl:template>
</xsl:stylesheet>

I assume the xsl:value-of part is not correct, but I don´t really know how to access the value of the Tag in the condition.

This seems a strange requirement. Assuming that "value" means a text node within an element (and not a value of an attribute), you could do simply:

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="text()[.='2']">
    <xsl:text>1</xsl:text>
</xsl:template>

</xsl:stylesheet>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM