You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XSLT中实现食谱分类及占比百分比计算?

XSLT实现食谱分类与占比统计

需求

  • 以食材数量平均值3为分界,将XML中的<pc:recipe>元素分为两类:
    • 食材数量过多:amount属性值≥4
    • 食材数量过少:amount属性值<3
  • 计算两类食谱的占比百分比,输出如下格式的XML结果:
<result> 
   <too_much_percentage>75</too_much_percentage>
   <too_few_percentage>25</too_few_percentage>
</result>

输入XML(已修正语法错误)

原输入XML存在标签不匹配问题(<pc:recipe>错误闭合为</pc:ingredient>),修正后的正确XML如下:

<?xml version="1.0" encoding="UTF-8"?>
<pc:recipes
  xmlns:pc="some-url-for-pc" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <pc:recipe amount="5"></pc:recipe>
  <pc:recipe amount="6"></pc:recipe>
  <pc:recipe amount="2"></pc:recipe>
  <pc:recipe amount="4"></pc:recipe> 
</pc:recipes>

解决方案:XSLT代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:pc="some-url-for-pc">

  <!-- 匹配根节点pc:recipes -->
  <xsl:template match="/pc:recipes">
    <result>
      <!-- 计算总食谱数量 -->
      <xsl:variable name="total-count" select="count(pc:recipe)" />
      <!-- 统计食材过多的食谱数量 -->
      <xsl:variable name="too-much-count" select="count(pc:recipe[@amount >= 4])" />
      <!-- 统计食材过少的食谱数量 -->
      <xsl:variable name="too-few-count" select="count(pc:recipe[@amount < 3])" />

      <!-- 计算并输出占比百分比 -->
      <too_much_percentage>
        <xsl:value-of select="round(($too-much-count div $total-count) * 100)" />
      </too_much_percentage>
      <too_few_percentage>
        <xsl:value-of select="round(($too-few-count div $total-count) * 100)" />
      </too_few_percentage>
    </result>
  </xsl:template>

</xsl:stylesheet>

代码说明

  1. 命名空间声明:引入pc命名空间,确保能正确匹配XML中的带前缀元素
  2. 变量定义:
    • total-count:统计所有<pc:recipe>元素的总数
    • too-much-count:筛选出amount≥4的食谱数量
    • too-few-count:筛选出amount<3的食谱数量
  3. 百分比计算:通过除法计算占比后乘以100,用round()函数确保结果为整数(符合示例输出)
  4. 结果输出:严格按照需求生成指定结构的XML结果

内容的提问来源于stack exchange,提问作者Rina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 13:48:19