Tyler Spivey, 31.03.2013 03:14:
In the below test script, I'm not getting the result I expect. Is this a bug in lxml? If not, what am I doing wrong? I'm using lxml 3.1.1 on win32, downloaded from PyPi.
What I get:
<root xmlns="url1"> <test attrib="value"/> </root>
I expect attrib to not lose its namespace, as shown when I re-parse the output:
lxml.etree.parse('test.xml').getroot()[0].attrib {'attrib': 'value'}
If I swap the append and the attribute setting, things work: <test xmlns:ns0="url1" ns0:attrib="value"/>
lxml.etree.parse('test.xml').getroot()[0].attrib {'{url1}attrib': 'value'}
If this is intended behaviour, I'll have to see how to fit that into my design, since my functions return elements ready for appending.
from lxml import etree
nsmap = {None: 'url1'} root = etree.Element('{url1}root', nsmap=nsmap) test = etree.Element('{url1}test') test.attrib['{url1}attrib'] = 'value' root.append(test) print etree.tostring(root, encoding='utf-8', pretty_print=True)
Your assumption about the default namespace is incorrect here. http://www.w3.org/TR/REC-xml-names/#defaulting Basically, attributes in the default namespace are badly defined. Don't use them. Instead, use an explicit namespace prefix for them, either by defining the namespace URI twice or by not using the default namespace at all. Stefan