简体   繁体   English

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

[英]Insert XML element to a specific location using ElementTree

I want to insert aaa into the parent "holding category" like the following: 我想将aaa插入父级“持有类别”,如下所示:

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

Here's the code I've written: 这是我编写的代码:

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

However, the the result I've received looks like this: 但是,我收到的结果如下所示:

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

with ns2:cost followed immediately after temporaryLocation instead of starting from the next line. 使用ns2:cost紧随临时位置之后,而不是从下一行开始。

ElementTree doesn't do "pretty printing" so if you want readable indentation you need to add it yourself. ElementTree不会进行“漂亮的打印”,因此,如果您想要可读的缩进,则需要自己添加。 I created an XML snippet similar to yours for illustration. 我创建了一个与您相似的XML代码段进行说明。 The indent function was obtained from an example on the ElementTree author's website (link) : indent功能是从ElementTree作者的网站(链接)上的示例获得的:

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)

Output: 输出:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM