我在尝试从xml获取数据时遇到问题,我得到了这个:
<?xml version="1.0" encoding="UTF-8"?>
<base>
<!-- OFFERS -->
<offers>
<offer status="1">Sale</offer>
<offer status="2">Rent</offer>
</offers>
<!--CATEGORIES-->
<categories>
<category cat="A">Category 1</category>
<category cat="B">Category 2</category>
<category cat="C">Category 3</category>
</categories>
<!--OBJECTS-->
<objects>
<object id="1" offer="1">
<name>Object 1</name>
<category cat="A"/>
<price>12</price>
</object>
<object id="2" offer="2">
<name>Object 1</name>
<category cat="B"/>
<price>1000</price>
</object>
<object id="3" offer="2">
<name>Object 1</name>
<category cat="A"/>
<price>10</price>
</object>
</objects>
<object id="4" offer="1">
<name>Object 1</name>
<category cat="C"/>
<price>60</price>
</object>
<object id="5" offer="2">
<name>Object 1</name>
<category cat="A"/>
<price>30</price>
</object>
</base>
对于每个类别,我需要知道租金价格的算术平均值(//要约/报价)
我的xsl:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr bgcolor="#9acd32">
<th>Category</th>
<th>AM</th>
</tr>
<xsl:for-each select="//categories/category">
<xsl:variable name="cat" select="@cat"/>
<xsl:variable name="object" select="//object[category/@cat=$cat]"/>
<xsl:variable name="qtobj" select="count($obj)"/>
<tr>
<td><xsl:value-of select="." /></td>
<td><xsl:value-of select="$object/price div $qtobj"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
我的主要问题是我不知道如何只过滤出租物品。
答案 0 :(得分:1)
如果我理解正确,你想做的事情如下:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:key name="obj" match="object" use="concat(category/@cat, '|', @offer)" />
<xsl:template match="/base">
<xsl:variable name="rent-status" select="offers/offer[.='Rent']/@status" />
<html>
<body>
<table border="1">
<tr bgcolor="#9acd32">
<th>Category</th>
<th>Average Price (Rent Only)</th>
</tr>
<xsl:for-each select="categories/category">
<xsl:variable name="objects" select="key('obj', concat(@cat, '|', $rent-status))" />
<tr>
<td>
<xsl:value-of select="." />
</td>
<td>
<xsl:value-of select="sum($objects/price) div count ($objects)"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
按照你的方式行事,你可以定义:
<xsl:variable name="objects" select="//object[category/@cat=current()/@cat and @offer=$rent-status]"/>
但使用key更高效,更优雅。