在现有 xml 文件中添加元素 python

add element in a existing xml file python

我有一个现有的 xml 文件如下:

<vehicleTravelTimeMeasurements>
        <vehicleTravelTimeMeasurement name="ckkkkkkkkkk" no="2">
            <start link="1" pos="3.864983"/>
            <end link="3" pos="23.275375"/>
        </vehicleTravelTimeMeasurement>
        <vehicleTravelTimeMeasurement name="" no="3">
            <start link="1" pos="3.864983"/>
            <end link="2" pos="13.275375"/>
        </vehicleTravelTimeMeasurement>
</vehicleTravelTimeMeasurements>

我正在尝试使用 xml.etree.cElementTree 构建与上面所示相同的格式,并将它们正确添加到 xml 中:

new = ET.Element("vehicleTravelTimeMeasurement", name = "kkk", no = "4")
newsub1 =  ET.Element("start", link = "1", pos="3.88888")
newsub2 = ET.Element("end",link = "3", pos = "3.88888")

有人可以帮我解决这个问题吗?

提前致谢!

您想使用 SubElement 并将 startend 元素添加到 vehicleTravelTimeMeasurement 元素。然后在位置 2 插入新创建的元素,因为 0 和 1 已经被占用。

import xml.etree.ElementTree as ET

def indent(elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

xml = '''<vehicleTravelTimeMeasurements>
        <vehicleTravelTimeMeasurement name="ckkkkkkkkkk" no="2">
            <start link="1" pos="3.864983"/>
            <end link="3" pos="23.275375"/>
        </vehicleTravelTimeMeasurement>
        <vehicleTravelTimeMeasurement name="" no="3">
            <start link="1" pos="3.864983"/>
            <end link="2" pos="13.275375"/>
        </vehicleTravelTimeMeasurement>
</vehicleTravelTimeMeasurements>'''

root = ET.fromstring(xml)
new = ET.Element("vehicleTravelTimeMeasurement", name = "kkk", no = "4")
newsub1 = ET.SubElement(new, "start", link = "1", pos="3.88888")
newsub2 = ET.SubElement(new, "end",link = "3", pos = "3.88888")
root.insert(2, new)
indent(root)
with open('test.xml', 'w') as f:
    f.write(ET.tostring(root))

简短版本/更新和编辑:

您唯一需要做的就是 (A) 添加 newsub1newsub2new。并且 (B) 将 new 添加到 root.

root = ET.fromstring(xml)  # or whichever way you're getting `root`
# these 3 lines form your code:
new = ET.Element('vehicleTravelTimeMeasurement', name="kkk", no="4")
newsub1 = ET.Element('start', link='1', pos='3.88888')
newsub2 = ET.Element('end', link='3', pos='3.88888')
# the next steps to add
new.append(newsub1)
new.append(newsub2)
root.append(new)

请注意,(A) 和 (B) 可以按任何顺序完成,并且可以缩短,如下所示:

>>> root = ET.fromstring(xml)
>>> new = ET.Element('vehicleTravelTimeMeasurement', name="kkk", no="4")
>>> root.append(new)  # note that I've immediately added `new`
>>> ET.SubElement(new, 'start', link='1', pos='3.88888')
<Element 'start' at 0x24707b8>
>>> ET.SubElement(new, 'end', link='3', pos='3.88888')
<Element 'end' at 0x24ea978>
>>> # there's no need to store the subelements in `newsub1` and
... # `newsub2` if you don't need to do anything with them
...
>>> indent(root)
>>> print ET.tostring(root)
<vehicleTravelTimeMeasurements>
  <vehicleTravelTimeMeasurement name="ckkkkkkkkkk" no="2">
    <start link="1" pos="3.864983" />
    <end link="3" pos="23.275375" />
  </vehicleTravelTimeMeasurement>
  <vehicleTravelTimeMeasurement name="" no="3">
    <start link="1" pos="3.864983" />
    <end link="2" pos="13.275375" />
  </vehicleTravelTimeMeasurement>
  <vehicleTravelTimeMeasurement name="kkk" no="4">
    <start link="1" pos="3.88888" />
    <end link="3" pos="3.88888" />
  </vehicleTravelTimeMeasurement>
</vehicleTravelTimeMeasurements>

备注:

  1. 我在创建 root 后就添加了 new
  2. 使用 append 而不是 insert 如果你知道你总是追加,而不是需要跟踪原始 xml 中的 no
    • 除非您无论如何都需要阅读它来计算下一个“no”属性
  3. ET.SubElement(new) 更新 new(和 root),即使 new 已经附加。
  4. 如果您不需要对子元素进行任何操作,则无需将子元素存储在 newsub1newsub2 中。
    • 第一种方法(如您的方法)创建元素,然后将它们添加到 root 或 new。
    • 第二种方法使用 ET.SubElement(new, ...) 将元素添加到其父元素。
  5. function indent is from here, which quotes this source.

Re # 4.2 以上,也可以这样做:

root = ET.fromstring(xml)
new = ET.SubElement(root, 'vehicleTravelTimeMeasurement', name="kkk", no="4")
# `new` is already created as a subelement of `root` and appended
ET.SubElement(new, 'start', link='1', pos='3.88888')
ET.SubElement(new, 'end', link='3', pos='3.88888')

来自Subelement docs:

This function creates an element instance, and appends it to an existing element.

(强调我的)