getting the attribute value using xslt

2 views
Skip to first unread message

SM

unread,
Jul 16, 2009, 2:14:54 PM7/16/09
to XSLT
Hi,
My xml sample data as below

<a>
<b>
<c test1 ="1">
<d> ass</d>
<e name="n1" number="12">
<row id="0">
<field name="valuetobetaken" type="string">
gfghg
</field>
<field name="test1" type="string1">
gfghg
</field>

</row>
<row id="1">
<field name="test2" type="string">
gfghg
</field>
<field name="test3" type="string1">
gfghg
</field>
</row>
</e>
</c>
</b>
</a>
I need to take the attribute value of name("valuetobetaken") from
the element field using xslt
<c test1 ="1">
<d> ass</d>
<e name="n1" number="12">
<row id="0">
<field name="valuetobetaken"

my xslt file as below

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:template match="/">
<xsl:variable name="test" select="." />
<xsl:for-each select ="$test/a/b">
<xsl:value-of select="c[@test1=1]/d[@name='n1'][@number=12]/row
[@id=12]/field[@name]">

</xsl:value-of>
</xsl:for-each>

</xsl:template>
</xsl:stylesheet>

the output is always coming as blank as below
<?xml version="1.0" encoding="utf-8"?>

attribute value is missing in the output.
is there any problem in the select statement of xsl?
I would like to know, how to take the attribute value, element value
of field for the above scenario

Thanks,
Sony

Andrew Hallagan

unread,
Jul 16, 2009, 3:14:26 PM7/16/09
to XS...@googlegroups.com
Given this:

<a>
<b>
<c test1="1">
    <d>aardvark</d>

    <e name="n1" number="12">
        <row id="0">
            <field name="valuetobetaken" type="string">gfghg</field>
            <field name="test1" type="string1">gfghg</field>
        </row>
        <row id="1">
            <field name="test2" type="string">gfghg</field>
            <field name="test3" type="string1">gfghg</field>
        </row>
    </e>
</c>
</b>
</a>

This stylesheet should do what you want.


<?xml version="1.0" encoding="UTF-8"?>

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>

<xsl:output method="xml"/>

<xsl:template match="d/text()"/>

<!-- select field elements that have a @name attribute -->
<xsl:template match="field[@name]">

  <!-- return the value of @name attribute -->
  <xsl:value-of select="./@name"/>

  <!-- insert a newline character -->
  <xsl:value-of select=" '&#xa;' "/>

</xsl:template>

</xsl:transform>


Notice that we need to write an explicit template to match against element "d", otherwise the default behaviour of the processor is to spit out the text inside that element.

AWH
Reply all
Reply to author
Forward
0 new messages