[lxml-dev] How to set an attribute with a xml-namepace
Stefan Behnel
stefan_ml at behnel.de
Tue Apr 28 15:48:45 CEST 2009
Grimm, Markus wrote:
> I want to set a new element with an attribute using the xml-namespace,
> f.e.
>
> >> xml = "<root xml:space=\"preserve\"/>"
> >> root = etree.fromstring(xml)
> >> print etree.tostring(root)
> <root xml:space="preserve"/>
>
> everything fine, and now...
>
>>> root = etree.Element("root", space="preserve")
>>> print etree.tostring(root)
> <root space="preserve"/>
>
> How can I bind the space-attribute to the xml-namespace, so I can output
> the same result as above ?
The namespace that is bound to the "xml" prefix is
http://www.w3.org/XML/1998/namespace
You use it like this:
>>> root = etree.Element("root",
... {'{http://www.w3.org/XML/1998/namespace}space' : "preserve"})
>>> print etree.tostring(root)
<root space="preserve"/>
Note that you have to pass a dictionary here as you cannot pass the name
as a keyword argument. Or use the .set() Element method.
Also see the section on namespaces in the tutorial.
Stefan
More information about the lxml-dev
mailing list