Yingqi Shi
Yingqi Shi

Reputation: 3

Insert XML element to a specific location using ElementTree

I want to insert aaa into the parent "holding category" like the following:

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

Upvotes: 0

Views: 2705

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177610

ElementTree doesn't do "pretty printing" so if you want readable indentation you need to add it yourself. I created an XML snippet similar to yours for illustration. The indent function was obtained from an example on the ElementTree author's website (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)

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>

Upvotes: 3

Related Questions