使用ElementTree将XML元素插入特定位置

时间:2017-11-02 16:19:04

标签: python xml elementtree

我想将aaa插入父“持有类别”中,如下所示:

<ns2:holding category="BASIC">
      <ns2:pieceDesignation>10010194589</ns2:pieceDesignation>
      <temporaryLocation>aaa</temporaryLocation>
      <ns2:cost>

这是我写的代码:

 temporarylocation = Element("temporaryLocation")`
 temporarylocation.text = 'aaa'
 holdingcategory.insert(1,temporarylocation)
 print(ET.tostring(holdingcategory))

然而,我收到的结果如下:

<ns2:pieceDesignation>10010194589</ns2:pieceDesignation>
    <temporaryLocation>aaa</temporaryLocation><ns2:cost>

使用ns2:cost紧跟在temporaryLocation后面而不是 从下一行开始。

1 个答案:

答案 0 :(得分:2)

ElementTree没有&#34;漂亮的印刷&#34;所以如果你想要可读的缩进,你需要自己添加它。我创建了一个类似于你的XML片段,用于说明。 indent函数是从ElementTree作者网站(link)上的示例获得的:

from xml.etree import ElementTree as et

xml = '''\
<doc>
  <holding category="BASIC">
    <pieceDesignation>10010194589</pieceDesignation>
  </holding>
</doc>'''

tree = et.fromstring(xml)
holdingcategory = tree.find('holding')
temporarylocation = et.Element("temporaryLocation")
temporarylocation.text = 'aaa'
holdingcategory.insert(1,temporarylocation)
et.dump(tree)

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

indent(tree)
print()
et.dump(tree)

输出:

<doc>
  <holding category="BASIC">
    <pieceDesignation>10010194589</pieceDesignation>
  <temporaryLocation>aaa</temporaryLocation></holding>
</doc>

<doc>
  <holding category="BASIC">
    <pieceDesignation>10010194589</pieceDesignation>
    <temporaryLocation>aaa</temporaryLocation>
  </holding>
</doc>