8

我试图用这个注册命名空间:

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

这有什么问题?


谢谢马丁尼

我试过 - 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:“元素”对象没有属性“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(更好的代码且易于阅读)

4

1 回答 1

19

关于如何使用命名空间和.findall().

.findall()函数(以及.iterfind .find()( .findtext() and) ) takes anamespaces` 参数应该是一个映射。这是查找标签时唯一参考的结构:

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

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

于 2013-01-02T15:23:08.743 回答