我的尝试
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))
但是我的代码会产生类似
的内容b'<Connection>\n <FileList> \n <File>/home/xyz/xml/text1.xml</File><File>/home/xyz/xml/text2.xml</File></FileList>\n</
Connection>\n'
我想要这样的东西
<Connection>
<FileList>
<File>/home/xyz/xml/text1.xml</File>
<File>/home/xyz/xml/text2.xml</File>
</FileList>
</Connection>
答案 0 :(得分:0)
你已经拥有了自己想要的东西。
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)
现在让我们看一下输出。
$ cat o.xml
<Connection>
<FileList>
<File>/home/xyz/xml/text1.xml</File><File>/home/xyz/xml/text2.xml</File></FileList>
</Connection>