创建XML插入头的Python代码

tmb3ates  于 2023-03-09  发布在  Python
关注(0)|答案(2)|浏览(154)

我有一个类似的代码来生成XML。代码类似于:

import xml.etree.ElementTree as ET
import requests
import json
import csv

data = ET.Element('XMLFORMPOST')

element0 = ET.SubElement(data, 'REQUEST')
element1 = ET.SubElement(data, 'LOGIN')
element2 = ET.SubElement(data, 'PARTNUM')
element2.text = str(ingramPartNumber)
element3 = ET.SubElement(data, 'LOOKUPTYPE')

b_xml = ET.tostring(data)
 with open("finalfile.xml", "wb") as f:
    f.write(b_xml)

我希望最终的XML具有如下所示的标头

<?xml version='1.0' encoding='utf8'?>

在帽子头之后是其余的元素。大致如下:

<?xml version='1.0' encoding='utf8'?>
<outer><inner>1</inner></outer>

我知道像“xml_declaration=True”这样的东西可以完成这项工作,但我不知道;I don“我不知道如何申请,也不知道是否有其他办法。
如何修改“with open”命令或执行其他操作来使用此脚本添加标题?

qv7cva1a

qv7cva1a1#

您应该使用ElementTree的write方法,如write(f, encoding='utf-8', xml_declaration=True)所述。
你的代码看起来像这样:

import xml.etree.ElementTree as ET

data = ET.Element('XMLFORMPOST')

element0 = ET.SubElement(data, 'REQUEST')
element1 = ET.SubElement(data, 'LOGIN')
element2 = ET.SubElement(data, 'PARTNUM')
element2.text = str(ingramPartNumber)
element3 = ET.SubElement(data, 'LOOKUPTYPE')

xml_doc = ET.ElementTree(element=data)
with open("finalfile.xml", "wb") as f:
    xml_doc.write(f, encoding='utf-8', xml_declaration=True)
jei2mxaa

jei2mxaa2#

你觉得这样有用吗?

import xml.etree.ElementTree as ET

data = ET.Element('XMLFORMPOST')
element_names = ('REQUEST', 'LOGIN', 'PARTNUM', 'LOOKUPTYPE')
elements = [ET.SubElement(data, current_tag) for current_tag in element_names]
elements[2].text = "ingramPartNumber"

document = ET.ElementTree(element=data)
document.write('final_file.xml', encoding='utf8')

相关问题