Question

My try

from lxml import objectify,etree
xml = """<?xml version='1.0' encoding='windows-1252'?>
<Connection>
  <FileList> 
  </FileList>
</Connection>"""

root = etree.fromstring(xml.encode('utf-8'))
e = root.find('.//FileList')
path = r'/home/xyz/xml/text'
extn = r'.xml'


for i in range(1,3):    
    file = etree.SubElement(e,'File')
    file.text = ''.join([path,str(i),extn])

print(etree.tostring(root,pretty_print=True))

But my code generates something like

b'<Connection>\n  <FileList> \n  <File>/home/xyz/xml/text1.xml</File><File>/home/xyz/xml/text2.xml</File></FileList>\n</
Connection>\n'

I want something like this

<Connection>
<FileList>
    <File>/home/xyz/xml/text1.xml</File>
    <File>/home/xyz/xml/text2.xml</File>
</FileList>
</Connection>
Was it helpful?

Solution

You already have what you want.

s = b'<Connection>\n  <FileList> \n  <File>/home/xyz/xml/text1.xml</File><File>/home/xyz/xml/text2.xml</File></FileList>\n</Connection>\n'
with open("o.xml", "w") as o:                                                                                                             
    print(s.decode("UTF-8"), file=o)

Now let's look at the output.

$ cat o.xml
<Connection>
  <FileList> 
  <File>/home/xyz/xml/text1.xml</File><File>/home/xyz/xml/text2.xml</File></FileList>
</Connection>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top