I am using lxml to manipulate some existing XML documents, and I want to introduce as little diff noise as possible. Unfortunately by default lxml.etree.XMLParser doesn't preserve whitespace before or after the root element of a document:
>>> xml = '\n <etaoin>shrdlu</etaoin>\n'
>>> lxml.etree.tostring(lxml.etree.fromstring(xml))
'<etaoin>shrdlu</etaoin>'
>>> lxml.etree.tostring(lxml.etree.fromstring(xml)) == xml
False
Is this possible using lxml? Is it supported by the underlying libxml2?
I don't know of any XML library that will do it for you. But using a regex sounds like a decent idea if you really need to do this.
>>> xml = '\n <etaoin>shrdlu</etaoin>\n'
>>> head, tail = re.findall(r"^\s*|\s*$", xml)[:2]
>>> root = etree.fromstring(xml)
>>> out = head + etree.tostring(root) + tail
>>> out == xml
True
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