如何将pandas DataFrame每一行填充至预定义UBL XML模板生成独立文件?
现有代码的核心问题
- 三引号字符串内的变量插入语法错误,直接在三引号里拼接df字段值的写法会触发Python语法报错
- 文件命名用的
index变量没有定义,循环内实际应该用循环标识作为文件名 - 字段和XML节点的映射关系错位,和示例输出的对应逻辑不匹配
- XML末尾多了一个多余的引号,会导致生成的XML格式非法,无法正常解析
可落地的实现方法
方法1:使用字符串占位符模板填充
先把固定不变的XML片段抽出来做成独立模板,把需要替换动态值的位置留好占位符,循环遍历每一行数据时,把当前行的字段值传入模板完成替换:
# 定义固定XML模板,动态值位置替换为命名占位符 XML_TEMPLATE = """<?xml version="1.0"?> <Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ccts="urn:un:unece:uncefact:documentation:2" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd"> <cbc:UBLVersionID>2.1</cbc:UBLVersionID> <cbc:CustomizationID>urn:www.cenbii.eu:transaction:biitrns010:ver2.0:extended:urn:www.peppol.eu:bis:peppol4a:ver2.0:extended:urn:www.simplerinvoicing.org:si:si-ubl:ver1.1.x</cbc:CustomizationID> <cbc:ProfileID>urn:www.cenbii.eu:profile:bii04:ver2.0</cbc:ProfileID> <cbc:ID>{invoice_id}</cbc:ID> <cbc:IssueDate>{total_amount}</cbc:IssueDate> <cbc:DueDate>{due_date}</cbc:DueDate> <cbc:InvoiceTypeCode listID="UNCL1001" listAgencyID="6">380</cbc:InvoiceTypeCode> <cbc:DocumentCurrencyCode>EUR</cbc:DocumentCurrencyCode> <cac:AccountingSupplierParty> """ # 逐行遍历DataFrame for row_index, row_data in df.iterrows(): # 按示例输出的映射关系替换为实际DataFrame列名 filled_content = XML_TEMPLATE.format( invoice_id = row_data["发票编号对应列名"], total_amount = row_data["总金额对应列名"], due_date = row_data["Factuurdatum"] ) # 用行索引发名文件,避免变量未定义问题 with open(f"invoice_{row_index}.xml", "w", encoding="utf-8") as save_file: save_file.write(filled_content)
方法2:使用f-string直接嵌入变量(Python3.6及以上版本支持)
如果觉得.format()写法繁琐,可以直接在字符串前加f前缀,把动态值直接嵌在字符串里,逻辑和上面完全一致:
for row_index, row_data in df.iterrows(): # 提前取出当前行需要的字段值,避免模板内写过长的索引 current_invoice_id = row_data["发票编号对应列名"] current_total = row_data["总金额对应列名"] current_factuur_date = row_data["Factuurdatum"] filled_content = f"""<?xml version="1.0"?> <Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ccts="urn:un:unece:uncefact:documentation:2" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd"> <cbc:UBLVersionID>2.1</cbc:UBLVersionID> <cbc:CustomizationID>urn:www.cenbii.eu:transaction:biitrns010:ver2.0:extended:urn:www.peppol.eu:bis:peppol4a:ver2.0:extended:urn:www.simplerinvoicing.org:si:si-ubl:ver1.1.x</cbc:CustomizationID> <cbc:ProfileID>urn:www.cenbii.eu:profile:bii04:ver2.0</cbc:ProfileID> <cbc:ID>{current_invoice_id}</cbc:ID> <cbc:IssueDate>{current_total}</cbc:IssueDate> <cbc:DueDate>{current_factuur_date}</cbc:DueDate> <cbc:InvoiceTypeCode listID="UNCL1001" listAgencyID="6">380</cbc:InvoiceTypeCode> <cbc:DocumentCurrencyCode>EUR</cbc:DocumentCurrencyCode> <cac:AccountingSupplierParty> """ with open(f"invoice_{row_index}.xml", "w", encoding="utf-8") as save_file: save_file.write(filled_content)
实操注意事项
- 保存文件时必须指定
encoding="utf-8",避免特殊字符出现乱码 - 把代码里的列名替换为你实际DataFrame对应的列名,映射关系对照示例输出调整即可
- 原代码中
cbc:DueDate标签后多写了一个英文引号,记得删除,否则生成的XML为非法格式 - 不推荐写
range(len(df))的循环写法,使用iterrows()遍历行的写法更符合pandas最佳实践,不容易出现索引错位的问题
内容的提问来源于stack exchange,提问作者Max den Hoed
相关产品推荐
相关产品推荐

