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

Python 使用ElementTree将XML元素插入到特定位置,python,xml,elementtree,Python,Xml,Elementtree,我想在母公司的“控股类别”中插入aaa,如下所示: <ns2:holding category="BASIC"> <ns2:pieceDesignation>10010194589</ns2:pieceDesignation> <temporaryLocation>aaa</temporaryLocation> <ns2:cost> 但是,我收到的结果如下所示: <ns2:piec

我想在母公司的“控股类别”中插入aaa,如下所示:

<ns2:holding category="BASIC">
      <ns2:pieceDesignation>10010194589</ns2:pieceDesignation>
      <temporaryLocation>aaa</temporaryLocation>
      <ns2:cost>
但是,我收到的结果如下所示:

<ns2:pieceDesignation>10010194589</ns2:pieceDesignation>
    <temporaryLocation>aaa</temporaryLocation><ns2:cost>
10010194589
aaa
对于ns2:成本紧跟在临时位置之后,而不是 从下一行开始。

ElementTree不会进行“漂亮的打印”,因此如果您想要可读的缩进,您需要自己添加它。我创建了一个与您的类似的XML片段,以供说明。
indent
函数来自ElementTree作者网站上的一个示例:

从xml.etree导入ElementTree作为et
xml=“”\
10010194589
'''
tree=et.fromstring(xml)
holdingcategory=tree.find('holding')
临时位置=等元素(“临时位置”)
temporarylocation.text='aaa'
holdingcategory.插入(1,临时位置)
et.dump(树)
def缩进(元素,级别=0):
i=“\n”+级别*”
如果len(elem):
如果不是elem.text或不是elem.text.strip():
elem.text=i+“”
如果不是elem.tail或不是elem.tail.strip():
elem.tail=i
对于elem中的elem:
缩进(元素,级别+1)
如果不是elem.tail或不是elem.tail.strip():
elem.tail=i
其他:
如果水平和(不是elem.tail或不是elem.tail.strip()):
elem.tail=i
缩进(树)
打印()
et.dump(树)
输出:

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

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

10010194589
aaa
10010194589
aaa
ElementTree不具备“漂亮的打印”功能,因此如果您想要可读的缩进,您需要自己添加它。我创建了一个与您的类似的XML片段,以供说明。
indent
函数来自ElementTree作者网站上的一个示例:

从xml.etree导入ElementTree作为et
xml=“”\
10010194589
'''
tree=et.fromstring(xml)
holdingcategory=tree.find('holding')
临时位置=等元素(“临时位置”)
temporarylocation.text='aaa'
holdingcategory.插入(1,临时位置)
et.dump(树)
def缩进(元素,级别=0):
i=“\n”+级别*”
如果len(elem):
如果不是elem.text或不是elem.text.strip():
elem.text=i+“”
如果不是elem.tail或不是elem.tail.strip():
elem.tail=i
对于elem中的elem:
缩进(元素,级别+1)
如果不是elem.tail或不是elem.tail.strip():
elem.tail=i
其他:
如果水平和(不是elem.tail或不是elem.tail.strip()):
elem.tail=i
缩进(树)
打印()
et.dump(树)
输出:

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

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

10010194589
aaa
10010194589
aaa

非常感谢您!这正是我想要的。非常感谢!这就是我想要的。
<doc>
  <holding category="BASIC">
    <pieceDesignation>10010194589</pieceDesignation>
  <temporaryLocation>aaa</temporaryLocation></holding>
</doc>

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