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

Insert XML element to a specific location using ElementTree

我想将 aaa 插入到父 "holding category" 中,如下所示:

<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>

with ns2:cost 紧跟在 temporaryLocation 之后,而不是 从下一行开始。

ElementTree 不会 "pretty printing" 所以如果你想要可读的缩进,你需要自己添加。我创建了一个类似于您的 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>