I have an xml I am parsing, making some changes and saving out to a new file. It has the declaration <?xml version="1.0" encoding="utf-8" standalone="yes"?>
which I would like to keep. When I am saving out my new file I am loosing the standalone="yes"
bit. How can I keep it in?
Here is my code:
templateXml = """<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<package>
<provider>Some Data</provider>
<studio_display_name>Some Other Data</studio_display_name>
</package>"""
from lxml import etree
tree = etree.fromstring(templateXml)
xmlFileOut = '/Users/User1/Desktop/Python/Done.xml'
with open(xmlFileOut, "w") as f:
f.write(etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8'))
Standalone. yes or no. It informs the parser whether the document relies on the information from an external source, such as external document type definition (DTD), for its content. The default value is set to no. Setting it to yes tells the processor there are no external declarations required for parsing the ...
The XML standalone element defines the existence of an externally-defined DTD. In the message tree it is represented by a syntax element with field type XML. standalone. The value of the XML standalone element is the value of the standalone attribute in the XML declaration.
lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers. This is when the lxml library comes to play.
You can pass standalone
keyword argument to tostring()
:
etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone=True)
Specify standalone
using tree.docinfo.standalone.
Try following:
from lxml import etree
tree = etree.fromstring(templateXml).getroottree() # NOTE: .getroottree()
xmlFileOut = '/Users/User1/Desktop/Python/Done.xml'
with open(xmlFileOut, "w") as f:
f.write(etree.tostring(tree, pretty_print=True, xml_declaration=True,
encoding=tree.docinfo.encoding,
standalone=tree.docinfo.standalone))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With