2013-01-02 28 views
6

我试图用这个注册命名空间:ElementTree的寄存器命名空间的错误

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

,但它不工作:

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 
>>> 

有什么错呢?


由于Martinj

我试图 - 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 

结果:(空)

2:

nsmap=root.nsmap 
print nsmap 

结果:AttributeError的:'元素'对象没有属性'ns地图”

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 

结果:工程确定。

是否有机会一次注册名称空间?然后我想使用listInvoice.find('inv:id')。text代替listInvoice.find('.// {http://www.stormware.cz/schema/version_2/invoice.xsd} id') .text(更好的代码和易于阅读)

+0

这个答案看起来很像你的http://stackoverflow.com/a/12861866/735204 –

回答

14

看起来文档尚未更新如何使用命名空间和.findall()

.findall()函数(以及.find().findtext() and .iterfind(),它被认为是一个映射) takes a namespaces`参数即找到代码时参考的唯一结构:

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

.register_namespace()功能只有当再次序列化一个树到文本时才有用

+0

谢谢,这个工程对于'.get()'我需要以“{namespace-URL}”作为前缀,例如。 'element.get({http://www.w3.org/1999/02/22-rdf-syntax-ns#} ID)'。 –

+1

@Vincent:是的,属性访问不支持名称空间前缀转换,您需要传入完全限定的名称空间前缀。 –