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

时间:2015-12-31 16:32:02

标签: python xml celementtree

我有一个现有的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")

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

提前谢谢!

2 个答案:

答案 0 :(得分:0)

您想使用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))

答案 1 :(得分:0)

短版/ 更新&amp;编辑:

您唯一需要做的就是(A)将newsub1newsub2添加到new。并且(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)&amp; (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. 我在创建它之后就已将new添加到root
  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 herequotes this source
  6. 上面的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

      

    此函数创建一个元素实例,附加到现有元素。

    (强调我的)