0

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.

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! This just gives me what I've wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.