如何使用XSL提取XML中四月的最高气温?
提取XML中四月最高气温的XSL解决方案
没问题,我来帮你搞定这个需求。针对你提供的XML结构,我们可以编写一个XSLT样式表,精准筛选出四月的天气数据并提取最高气温。
首先先确认你的源XML结构(方便对照):
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="THISISA3.xsl"?> <forecast qTime="28/10/20 10:00 PM" qLocation="Singapore"> <weather yyyymmdd="20200430"> <year>2020</year> <month>04</month> <date>30</date> <comment>Plenty of sunshine</comment> <code>sunny</code> <highest>32.6</highest> <lowest>28.4</lowest> </weather> <weather yyyymmdd="20200421"> <year>2020</year> <month>04</month> <date>21</date> <comment>Plenty of sunshine</comment> <code>sunny</code> <highest>32.2</highest> <lowest>29.8</lowest> </weather> </forecast>
接下来创建名为THISISA3.xsl的样式表文件,代码如下:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 匹配根节点<forecast> --> <xsl:template match="/forecast"> <html> <body> <h2>新加坡四月最高气温统计</h2> <h3>每日最高气温</h3> <ul> <!-- 核心筛选:只选中month值为"04"的weather节点 --> <xsl:for-each select="weather[month='04']"> <li> <xsl:text>日期:</xsl:text> <xsl:value-of select="year"/>-<xsl:value-of select="month"/>-<xsl:value-of select="date"/> <xsl:text> | 最高气温:</xsl:text> <xsl:value-of select="highest"/>℃ </li> </xsl:for-each> </ul> <!-- 可选:计算四月的最高气温极值 --> <h3>四月最高气温极值</h3> <p> <xsl:text>全月最高气温:</xsl:text> <xsl:value-of select="max(weather[month='04']/highest)"/>℃ </p> </body> </html> </xsl:template> </xsl:stylesheet>
关键逻辑说明
- 筛选四月数据:
<xsl:for-each select="weather[month='04']">这行是核心,通过谓词[month='04']精准过滤出所有四月的天气条目 - 提取最高气温:
<xsl:value-of select="highest"/>直接获取对应条目的最高气温值 - 极值计算(可选):使用
max(weather[month='04']/highest)可以快速算出四月所有最高气温中的最大值,不需要的话可以删除这部分代码
把这两个文件放在同一目录下,用浏览器打开XML文件,就能看到格式化后的四月最高气温数据啦。
内容的提问来源于stack exchange,提问作者user14482437
相关产品推荐
相关产品推荐

