简体   繁体   中英

use xsl modify property value inside xml tag

say this is my xml

<?xml version="1.0" encoding="UTF-8"?>
<node>
    <file name="abc.txt.bak">
        <fileid value="112358"/>
    </file>
    <location value="Baker Street"/>
</node>

I want to use xsl to transform this xml, by removing the .bak of file name. The expected result is like this:

<?xml version="1.0" encoding="UTF-8"?>
<node>
     <file name="abc.txt">
         <fileid value="112358"/>
     </file>
     <location value="Baker Street"/>
</node>

my xsl file is like this, which does not work. It just copies everything without changing the value.

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

   <xsl:template match="node/file/@name" >
        <xsl:copy>
            <xsl:attribute name="name">
                <xsl:value-of select="substring-before(., '.bak')" />
            </xsl:attribute>
        </xsl:copy>
   </xsl:template>
</xsl:stylesheet>

I've solved my own question. Just to share.

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="node/file">

        <xsl:variable name="bak_file_name">
            <xsl:value-of select="@name" />
        </xsl:variable>

        <xsl:copy>
            <xsl:apply-templates select="@*"/> 
                <xsl:attribute name="name">
                            <xsl:value-of select="substring-before($bak_file_name, '.bak')" />
                </xsl:attribute>
            <xsl:apply-templates select="fileid"/> 
        </xsl:copy>


    </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