Re: [xsl] <xsl:attribute issue

Subject: Re: [xsl] <xsl:attribute issue
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Wed, 16 May 2007 13:59:22 +0200
Vaduvoiu Tiberiu wrote:
Hi, I am trying to create an attribute for one of my xml files that has a typoical format like:
<root>
    <level1>
            <name>Name1</name>
            other tags
    </level1>
    <level1>
            <name>Name2</name>
            other tags
    </level1>
</root>

so I'm trying to set the attribute of the name element before displaying it:

<xsl:for-each select=level1>
    <xsl:variable ....{here I get a variable so that's why I can't call directly for each level1/name>

<xsl:for-each select="name">
    <xsl:attribute name="test">
            <xsl:value-of select="4"/>(just for testing, instead of 4 I have a variable but I put 4 for testing)
</xsl:attribute>
<xsl:for-each>
</xsl:for-each>


and then if I try to display it using
<xsl:for-each select="level1/name">
<xsl:value-of select="@test"/>
</xsl:for-each>,


it doesn't display anything.

I wonder what you mean with "display" as XSLT is a transformation language and cannot display anything.


From what you read above I got the faint impression that you think you can build an element during transformation (level1/name) and then transform that same element again and request the value of that attribute. Also, you seem to think that you can have any multitude of attributes with the same name on an element (you use xsl:for-each) which is not possible because it is not XML.

You create an attribute like this:
<xsl:attribute name="bla">value</xsl:attribute>

but it must be a direct child of an element, like this:
<lre-element>
  <xsl:attribute name="bla">value</xsl:attribute>
</lre-element>

if the value is literate, you don't need to use xsl:attribute
<lre-element bla="value" />

if the value can be expressed with an xpath expression (as opposed to, say, apply-templates or another for-each), you can use an AVT:
<lre-element bla="{path/to/value}" />


Because it seems likely that you have not yet understood the XSLT processing model, or the basic ideas behind it, consider reading a tutorial. There are plenty on the web and I can recommend the books of Jeni Tenison fo starters and Michael Kay's for reference.

Good luck coding
-- Abel Braaksma

PS: your original inquiry seems to be about enhancing existing XML with a couple attributes. Look up the modified copy template which will look something like the following in your case:


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

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

Current Thread