Elementtree element case register namespace error

I tried registering the namespace with this:

ET.register_namespace("inv", "http://www.stormware.cz/schema/version_2/invoice.xsd") 

but it does not work:

 Traceback (most recent call last): File "C:\tutorial\temp_xml2.py", line 34, in module> for listInvoice in root.findall('inv:invoiceHeader'): File "C:\Python27\LIB\xml\etree\ElementTree.py", line 390, in findall return ElementPath.findall(self, path, namespaces) File "C:\Python27\LIB\xml\etree\ElementPath.py", line 293, in findall return list(iterfind(elem, path, namespaces)) File "C:\Python27\LIB\xml\etree\ElementPath.py", line 259, in iterfind token = next() File "C:\Python27\LIB\xml\etree\ElementPath.py", line 83, in xpath_tokenizer raise SyntaxError("prefix %r not found in prefix map" % prefix) SyntaxError: prefix 'inv' not found in prefix map >>> 

what is wrong with it?


Thanks Martinj

I tried - 1 ..:

 for listInvoice in root.findall('inv:invoiceHeader', namespaces=dict(inv='http://www.stormware.cz/schema/version_2/invoice.xsd')): invoiceHeader = listInvoice.find('inv:id', namespaces=dict(inv='http://www.stormware.cz/schema/version_2/invoice.xsd')).text print invoiceHeader 

Result: (empty)

2 :.

 nsmap=root.nsmap print nsmap 

Result: AttributeError: the 'Element' object does not have the 'nsmap' attribute

3 .:

 for listInvoice in root.findall('.//{http://www.stormware.cz/schema/version_2/invoice.xsd}invoiceHeader'): invoiceHeader = listInvoice.find('.//{http://www.stormware.cz/schema/version_2/invoice.xsd}id').text print invoiceHeader 

Result: working fine.

Is it possible to register namespaces at the same time? Then I would like to use listInvoice.find ('inv: id'). Text instead of listInvoice.find ('.// ​​{http://www.stormware.cz/schema/version_2/invoice.xsd} id'). Text (more convenient code and easy to read)

+6
source share
1 answer

It seems that the documentation has not been updated on how to use namespaces and .findall() .

The .findall() function (as well as .find() , .findtext() and .iterfind () ) takes a argument namespaces`, which must be a match. This is the only structure that has been accessed when searching for tags:

 root.findall('inv:invoiceHeader', namespaces=dict(inv='http://www.stormware.cz/schema/version_2/invoice.xsd')) 

The .register_namespace() function is only useful when re-serializing a tree for text.

+14
source

All Articles