Home > Blockchain >  Proper way to set an attribute of nth element with XSLT
Proper way to set an attribute of nth element with XSLT

Time:11-14

I have the following xml:

<t>
    <property>value1</property>
    <property type="oldtype">value2</property>
    <property type="oldtype">value3</property>
    <property type="oldtype">value4</property>
</t>

I want to set the type attribute of the second property element with XSLT.

Currently I have the following XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:param name="pNewType" select="'newtype'"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="property[2]/@type">
        <xsl:attribute name="type">
            <xsl:value-of select="$pNewType"/>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

It works well with xsltproc and online xslt tools, but does not work with Qt's XSLT implementation. Is this the right way to do this transformation?

Qt's isValid() check function returns true, but the result of the transformation is the same as the input.

The expected output is:

<t>
    <property>value1</property>
    <property type="newtype">value2</property>
    <property type="oldtype">value3</property>
    <property type="oldtype">value4</property>
</t>

(without the "index"[2], it works as expected, change all attributes)

CodePudding user response:

Yes that ought to work, and must be a bug in QT's XSLT implementation.

You might want to try something that's semantically equivalent but syntactically different to see if you can work around the bug.

The match expression is actually just a shorthand for:

property[position()=2]/@type

If that doesn't work you could try:

property[count(preceding-sibling::property)=1]/@type
  • Related