如何将新节点添加到 XML 树中,从 Python 中的列表读取?

How to add new nodes into XML tree, reading from a list in Python?

我正在尝试从 list 读取并将值作为新节点添加到 Python

中的 XML
list = ['163','164','165']

并在将列表值附加到节点 trackingnumbers

之后

xml 应该是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<trackingrequest>
<user>TAIL</user>
<password>20</password>
<trackingnumbers>
    <trackingnumber>163</trackingnumber>
    <trackingnumber>164</trackingnumber>
    <trackingnumber>165</trackingnumber>
</trackingnumbers>
</trackingrequest>

到目前为止我已经明白了,但我一直坚持在循环中创建 dynamic variables,这会在 trackingnumbers

中创建新节点
def GenerateXML():

    root = ET.Element("trackingrequest")
    m1 = ET.Element("user")
    root.append(m1)
    m1.text = 'TAIL'

    m2 = ET.Element("password")
    root.append(m2)
    m2.text = '20'

    m3 = ET.Element("trackingnumbers")
    root.append(m3)
    d = {}

    for i in range(list):
       d["trackingid_{0}".format(i)] = ET.SubElement(m3, "trackingnumber")
       d['trackingid_1'].text = i*2

    tree = ET.ElementTree(root)

思路是找到trackingnumbers并添加需要的子元素

import xml.etree.ElementTree as ET

lst = ['163', '164', '165']

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<trackingrequest>
<user>TAIL</user>
<password>20</password>
<trackingnumbers>

</trackingnumbers>
</trackingrequest>'''

root = ET.fromstring(xml)
tracking_numbers = root.find('.//trackingnumbers')
for num in lst:
    tn = ET.SubElement(tracking_numbers, 'trackingnumber')
    tn.text = num
ET.dump(root)

输出

<?xml version="1.0" encoding="UTF-8"?>
<trackingrequest>
   <user>TAIL</user>
   <password>20</password>
   <trackingnumbers>
      <trackingnumber>163</trackingnumber>
      <trackingnumber>164</trackingnumber>
      <trackingnumber>165</trackingnumber>
   </trackingnumbers>
</trackingrequest>