Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter a single attribute with XSLT

Tags:

xml

xslt

What's the simplest XSLT you can think of to transform the value of the first, in this case only, /configuration/system.web/compilation/@debug attribute from true to false?

like image 295
Pete Montgomery Avatar asked Jun 07 '10 21:06

Pete Montgomery


People also ask

What is one way to add an attribute to an element in XSLT?

Attributes can be added or modified during transformation by placing the <xsl:attribute> element within elements that generate output, such as the <xsl:copy> element. Note that <xsl:attribute> can be used directly on output elements and not only in conjunction with <xsl:element> .

How do you declare a variable and assign value in XSLT?

XSLT <xsl:variable>The <xsl:variable> element is used to declare a local or global variable. Note: The variable is global if it's declared as a top-level element, and local if it's declared within a template. Note: Once you have set a variable's value, you cannot change or modify that value!

How do I select a substring in XSLT?

XSLT doesn't have any new function to search Strings in a reverse manner. We have substring function which creates two fields substring-before-last and substring-after-last.In XSLT it is defined as follows: <xsl:value-of select="substring (string name ,0, MAX_LENGTH )"/>...


1 Answers

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match="system.web/compilation[1]/@debug">
  <xsl:attribute name="debug">false</xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<configuration>
    <system.web>
        <compilation debug="true" defaultLanguage="C#">
            <!-- this is a comment -->
        </compilation>

        <compilation debug="true" defaultLanguage="C#">
            <!-- this is another comment -->
        </compilation>
    </system.web>
</configuration>

produces the wanted, correct result: modifies the debug attribute of the first compilation child of any system.web element (but we know that there is only one system.web element in a config file.

<configuration>
    <system.web>
        <compilation debug="false" defaultLanguage="C#">
            <!-- this is a comment -->
        </compilation>
        <compilation debug="true" defaultLanguage="C#">
            <!-- this is another comment -->
        </compilation>
    </system.web>
</configuration>

As we see, only the first debug atribute is modifird to false, as required.

like image 90
Dimitre Novatchev Avatar answered Oct 01 '22 14:10

Dimitre Novatchev