You need to enable JavaScript to run this app. 如何对多条XML记录执行计算?如给价格加5%并四舍五入到美元
优惠活动
大模型
产品
解决方案
定价
更多

如何对多条XML记录执行计算?如给价格加5%并四舍五入到美元

XML批量更新price字段的实现方案

你需要实现的是遍历XML中所有<price>节点,将数值乘以1.05后四舍五入为整数,以下是3种常用的实现方式:

1. Python 实现(无额外依赖,通用性最强)

使用Python标准库xml.etree.ElementTree即可完成操作,不需要安装第三方包:

import xml.etree.ElementTree as ET

# 解析XML文件
tree = ET.parse("你的文件路径.xml")
root = tree.getroot()

# 遍历所有book节点下的price
for price in root.iter("price"):
    original_val = float(price.text)
    new_val = round(original_val * 1.05)
    price.text = str(new_val)

# 保存修改后的XML
tree.write("修改后文件.xml", encoding="UTF-8", xml_declaration=True)

运行后你提供的示例XML中两个price会分别修改为32、31。

2. XSLT 实现(适合XML转换场景)

编写XSLT样式表update_price.xsl如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- 原样复制所有节点和属性 -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <!-- 匹配price节点执行计算 -->
    <xsl:template match="price">
        <xsl:copy>
            <xsl:value-of select="round(./text() * 1.05)"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

使用XSLT处理器(如xsltproc)执行转换:
xsltproc update_price.xsl 原文件.xml > 修改后文件.xml

3. 命令行实现(适合Linux/macOS终端快速操作)

安装xmlstarlet工具后,一行命令即可完成修改:

xmlstarlet edit -u "//price" -x "round(./text() * 1.05)" 原文件.xml > 修改后文件.xml

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 16:45:03