views:

236

answers:

2

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?

+1  A: 

Capture the whitespace with a regex and add it back to the string when you're done.

SpliFF
A: 

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
Filip Salomonsson