Reputation: 929
My XML codes:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="book.xslt"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>20.30</price>
</book>
<book>
<title lang="fr">Exploitation Linux</title>
<price>40.00</price>
</book>
</bookstore>
My XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr>
<th>Book Title</th>
<th>Price</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title[@lang='eng']/text()"/></td>
<td><xsl:value-of select="price/text()"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
I would like to display the details only for the title which have attribute lang="eng"
but i'm getting an unnecessary row where there's no book title but there's the price. Here's the output.
Thanks for your help.
Upvotes: 0
Views: 1065
Reputation: 122364
You need to limit the elements you're processing with the for-each
to those that have a title in the appropriate language:
<xsl:for-each select="bookstore/book[title/@lang = 'eng']">
As an aside, you almost never need to use text()
in an XPath expression, unless you really do want to handle individual text nodes separately. In situations like yours, where what you care about is the text content of the whole element, just take the value-of
the element itself:
<td><xsl:value-of select="price"/></td>
Upvotes: 1