使用XSLT将XML转CSV,为多Warning节点生成对应多行数据
解决方案:基于XSLT的XML转CSV修改方案
核心思路是以Warning节点为遍历单位,而非原方案中的UpdateStep节点,同时从Warning的父节点UpdateStep中提取共享的Phase、时间戳等字段,确保每个Warning对应一行CSV数据。
1. 示例XML结构
假设你的XML输入格式如下:
<Root> <UpdateStep> <Phase>Deployment</Phase> <Timestamp>2024-05-20T10:30:00</Timestamp> <Warning>Missing configuration file</Warning> <Warning>Permission denied on directory</Warning> </UpdateStep> <UpdateStep> <Phase>Testing</Phase> <Timestamp>2024-05-20T11:15:00</Timestamp> <Warning>Test case failed: Login</Warning> </UpdateStep> <UpdateStep> <Phase>Cleanup</Phase> <Timestamp>2024-05-20T12:00:00</Timestamp> <!-- 无Warning节点的情况 --> </UpdateStep> </Root>
2. 修改后的XSLT转换规则
创建transform.xslt文件,内容如下:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="UTF-8"/> <!-- 输出CSV表头 --> <xsl:template match="/"> <xsl:text>Phase,Timestamp,Warning </xsl:text> <!-- 遍历所有Warning节点,生成对应行 --> <xsl:apply-templates select="//UpdateStep/Warning"/> <!-- 处理无Warning的UpdateStep,生成空Warning行 --> <xsl:apply-templates select="//UpdateStep[not(Warning)]"/> </xsl:template> <!-- 为每个Warning生成一行数据 --> <xsl:template match="Warning"> <!-- 提取父节点UpdateStep的Phase --> <xsl:value-of select="../Phase"/> <xsl:text>,</xsl:text> <!-- 提取父节点UpdateStep的Timestamp --> <xsl:value-of select="../Timestamp"/> <xsl:text>,</xsl:text> <!-- 转义Warning内容中的逗号/引号,避免CSV格式错误 --> <xsl:call-template name="escape-csv"> <xsl:with-param name="text" select="."/> </xsl:call-template> <xsl:text> </xsl:text> </xsl:template> <!-- 处理无Warning的UpdateStep --> <xsl:template match="UpdateStep[not(Warning)]"> <xsl:value-of select="Phase"/> <xsl:text>,</xsl:text> <xsl:value-of select="Timestamp"/> <xsl:text>, </xsl:text> </xsl:template> <!-- 辅助模板:CSV内容转义逻辑 --> <xsl:template name="escape-csv"> <xsl:param name="text"/> <xsl:choose> <xsl:when test="contains($text, ',') or contains($text, '"')"> <xsl:text>"</xsl:text> <xsl:value-of select="translate($text, '"', '""')"/> <xsl:text>"</xsl:text> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text"/> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
3. Python中调用XSLT的代码
使用lxml.etree执行转换:
from lxml import etree # 加载XML和XSLT文件 xml_tree = etree.parse("input.xml") xslt_transform = etree.XSLT(etree.parse("transform.xslt")) # 执行转换并保存结果 result = xslt_transform(xml_tree) with open("output.csv", "w", encoding="utf-8") as f: f.write(str(result))
关键修改说明
- 遍历对象从
UpdateStep改为Warning,确保每个警告生成独立行 - 通过
../语法访问父节点UpdateStep的共享字段,保留上下文信息 - 新增CSV内容转义逻辑,避免内容中的逗号、引号破坏格式
- 补充处理无
Warning的UpdateStep节点,确保数据完整性
内容的提问来源于stack exchange,提问作者Ana Filipa Ferreira
相关产品推荐
相关产品推荐

