【问题标题】:Pandas to_xml() Setting xml prefixPandas to_xml() 设置 xml 前缀
【发布时间】:2022-12-07 14:14:28
【问题描述】:

我正在尝试使用 pd.to_xml() 从 pandas 数据帧编写 xml 并获得以下输出:

代码:

# Write pandas dataframe to custom xml format

namespaces = {
    'ns0': "urn:sca:com:edi:mappings:aust:b2be:inbounddeliverydate"
}

with open('Inb.xml', 'w') as myfile: 
  myfile.write(data.to_xml(index=False, 
                            root_name='MT_InboundDeliveryDate', 
                            row_name='Row', 
                            namespaces=namespaces, 
                            prefix='ns0'))

输出:

<?xml version='1.0' encoding='utf-8'?>
<ns0:MT_InboundDeliveryDate xmlns:ns0="urn:sca:com:edi:mappings:aust:b2be:inbounddeliverydate">
  <ns0:Row>
    <ns0:InboundID>355555106537455</ns0:InboundID>
    <ns0:DocumentDate/>
    <ns0:LFDAT>19082022</ns0:LFDAT>
  </ns0:Row>
  <ns0:Row>
    <ns0:InboundID>35555552066774536</ns0:InboundID>
    <ns0:DocumentDate/>
    <ns0:LFDAT>03012023</ns0:LFDAT>
  </ns0:Row>
</ns0:MT_InboundDeliveryDate>

但是,我需要前缀只适用于 root_name 而不是每一行

所需输出:

<?xml version='1.0' encoding='utf-8'?>
<ns0:MT_InboundDeliveryDate xmlns:ns0="urn:sca:com:edi:mappings:aust:b2be:inbounddeliverydate">
  <Row>
    <InboundID>355555106537455</InboundID>
    <DocumentDate/>
    <LFDAT>19082022</LFDAT>
  </Row>
  <Row>
    <InboundID>35555552066774536</InboundID>
    <DocumentDate/>
    <LFDAT>03012023</LFDAT>
  </Row>
</ns0:MT_InboundDeliveryDate>

我想实现上述所需的输出以自动执行我的系统更新脚本。

【问题讨论】:

    标签: python pandas xml prefix


    【解决方案1】:

    修复很简单:

    namespaces = {
        "ns0":"urn:sca:com:edi:mappings:aust:b2be:inbounddeliverydate"
    }
    
    with open('Inb.xml', 'w') as myfile: 
      myfile.write(data.to_xml(index=False,
                                row_name="Row",
                                root_name=QName(namespaces["ns0"],'MT_InboundDeliveryDate')))
    
    

    【讨论】: