Skip to content Skip to sidebar Skip to footer

Setting 'xml:space' To 'preserve' Python Lxml

I have a text element within an SVG file that I'm generating using lxml. I want to preserve whitespace in this element. I create the text element and then attempt to .set() the xml

Solution 1:

You can do it by explicitly specifying the namespace URI associated with the special xml: prefix (see http://www.w3.org/XML/1998/namespace).

from lxml import etree

root = etree.Element("root")
root.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")

print etree.tostring(root)

Output:

<rootxml:space="preserve"/>

Post a Comment for "Setting 'xml:space' To 'preserve' Python Lxml"