Issue
I want to include the XML prolog in my XML file... I tried the following -
ET.tostring(root, encoding='utf8', method='xml')
But it works only while printing and not for writing to file. I have a small code where I am changing an attribute and modifying the XML file. But I want to add the XML prolog also. Any idea how to ?
import xml.etree.ElementTree as ET
tree = ET.parse('xyz.xml')
root = tree.getroot()
root[0].text = 'abc'
ET.tostring(root, encoding='utf8', method='xml')
tree.write('xyz.xml')
Solution
Using lxml.etree
does it:
import lxml.etree
xml = lxml.etree.parse('xyz.xml')
root = xml.getroot()
root[0].text = 'abc'
with open("xyz2.xml", 'wb') as f:
f.write(lxml.etree.tostring(root, xml_declaration=True, encoding="utf-8"))
print(open("xyz2.xml", 'r').read())
Output:
<?xml version='1.0' encoding='utf-8'?>
<note>
<to>abc</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Answered By - Maurice Meyer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.