Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting 'xml:space' to 'preserve' Python lxml

Tags:

python

xml

svg

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:space to preserve but nothing I try seems to work. I'm probably missing something conceptually. Any ideas?

like image 770
Saar Drimer Avatar asked Jul 04 '13 19:07

Saar Drimer


People also ask

What is lxml Etree in Python?

lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.

What is lxml Etree _element?

Returns a sequence or iterator of all elements in the subtree in document order (depth first pre-order), starting with this element. Can be restricted to find only elements with specific tags, see iter. Deprecated: Note that this method is deprecated as of ElementTree 1.3 and lxml 2.0.

Is lxml default in Python?

It almost is. lxml is not written in plain Python, because it interfaces with two C libraries: libxml2 and libxslt.


1 Answers

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:

<root xml:space="preserve"/>    
like image 83
mzjn Avatar answered Sep 27 '22 23:09

mzjn