在Google Sheets中用IMPORTXML+XQuery按产品节点重复提取开票人名称
解决方案:按每个商品描述重复输出开票人名称
问题描述
我需要从开票程序导出的简化XML数据中,针对每个<productDescription>节点,提取对应的<invoicerName>节点,期望查询结果重复返回该节点(如下示例)。我尝试了多种方法,但无法得到重复的invoicerName值。
附XML数据:
<?xml version="1.0" encoding="UTF-8"?> <invoices> <invoice> <invoicerInfo> <invoicerName>Jack</invoicerName> </invoicerInfo> <invoiceDetails> <productDescription>Soda</productDescription> <productDescription>Popcorn</productDescription> <productDescription>Tickets</productDescription> </invoiceDetails> </invoice> </invoices>
期望输出:
Element='<invoicerName>Jack</invoicerName>' Element='<invoicerName>Jack</invoicerName>' Element='<invoicerName>Jack</invoicerName>'
实现方法
方法1:Python + lxml库
遍历每个<productDescription>节点,再通过相对路径回溯到同发票下的<invoicerName>节点,重复输出结果:
from lxml import etree # 加载XML内容 xml_content = """<?xml version="1.0" encoding="UTF-8"?> <invoices> <invoice> <invoicerInfo> <invoicerName>Jack</invoicerName> </invoicerInfo> <invoiceDetails> <productDescription>Soda</productDescription> <productDescription>Popcorn</productDescription> <productDescription>Tickets</productDescription> </invoiceDetails> </invoice> </invoices>""" tree = etree.fromstring(xml_content) # 遍历商品描述节点,关联输出开票人名称 for product in tree.xpath('//productDescription'): invoicer_node = product.xpath('../../invoicerInfo/invoicerName')[0] print(f"Element='{etree.tostring(invoicer_node, encoding='unicode')}'")
方法2:XSLT转换
编写XSLT样式表,通过遍历商品描述节点实现重复输出:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:for-each select="//productDescription"> <xsl:text>Element='</xsl:text> <xsl:copy-of select="../../invoicerInfo/invoicerName"/> <xsl:text>' </xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet>
使用XSLT处理器(如xsltproc命令行工具)处理XML和上述样式表,即可得到目标输出。
关键思路
问题核心是将每个商品描述与所属发票的开票人绑定,而非直接提取开票人节点。直接选取//invoicerName只会返回一次结果,通过遍历商品描述节点,再通过相对路径回溯到对应开票人节点,就能实现按商品数量重复输出的效果。
内容的提问来源于stack exchange,提问作者Luis Flores
相关产品推荐
相关产品推荐

