elementtree注册名称空间错误

时间:2013-01-02 15:10:11

标签: python 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:'Element'对象没有属性'nsmap'

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(更好的代码,易于阅读)

1 个答案:

答案 0 :(得分:15)

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

.findall()函数(以及.find().findtext() and。iterfind()) takes a名称空间`参数应该是一个映射。这是唯一的结构查找标签时咨询:

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

.register_namespace()函数仅在将树再次序列化为文本时有用。

相关问题