Reputation: 129
I'm new to the XSL and have this question, so I have this XML
<a>
<b>
<c1>
<d>N1</d>
<e>Test</e>
</c1>
<c1>
<d>N1</d>
<e>Test2</e>
</c1>
</b>
</a>
So I want to get the value test2 so, here is my statement, which it doesnt work:
<xsl:for-each select="//b/c1[2]">
<xsl:if test="d = N1">
<data>
<xsl:value-of select="e"/>
</data>
</xsl:if>
</xsl:for-each>
Upvotes: 0
Views: 104
Reputation: 30991
Your source XML contains some mistakes.
The first thing to correct is to change <e>Test/<e>
to <e>Test</e>
(the slash should be after <
, to form the closing tag.
Then look at <xsl:for-each select="//b/c1[2]">
in your XSLT.
c1[2]
means that you want the second element with c1
name.
So the secont thing to change is change <c2> ... </c2>
to
<c1> ... </c1>
, thus you will have the second c1
element.
As a result, your source XML should be as follows:
<a>
<b>
<c1>
<d>N1</d>
<e>Test</e>
</c1>
<c1>
<d>N1</d>
<e>Test2</e>
</c1>
</b>
</a>
Another important thing is that you cannot start the XSLT script
with just <xsl:for-each...
.
You must start with <xsl:stylesheet
as the main tag.
Then, e.g. in a template matching /
there shoud be placed
some main tag (I called it just main
, see below), and
within it there can be placed your for-each
loop.
The next correction pertains to <xsl:if test="d = N1">
.
Change it to <xsl:if test="d = 'N1'">
, because N1
is a
string constant, not a tag name.
So the whole XSLT script can be e.g.:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:output indent="yes"/>
<xsl:template match="/">
<main>
<xsl:for-each select="//b/c1[2]">
<xsl:if test="d = 'N1'">
<data>
<xsl:value-of select="e"/>
</data>
</xsl:if>
</xsl:for-each>
</main>
</xsl:template>
</xsl:stylesheet>
and it gives:
<?xml version="1.0" encoding="UTF-8"?>
<main>
<data>Test2</data>
</main>
Upvotes: 1