elementtree注册名称空间错误 [英] elementtree register namespace error

查看:47
本文介绍了elementtree注册名称空间错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下方法注册名称空间:

I tried to register namespace with this:

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'

Result: AttributeError: 'Element' object has no attribute '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(更清晰,更易于阅读的代码)

Is there any chance to register namespaces at once? 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 (nicer code and easy to read)

推荐答案

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

It looks like the documentation hasn't been updated on how to use namespaces and .findall().

.findall()函数(以及 .find() .findtext()和 .iterfind())接受一个 namespaces`参数成为一个映射。这是查找标记时查询的唯一结构:

The .findall() function (as well as .find(), .findtext() and.iterfind()) takes anamespaces` argument which is supposed to be a mapping. That is the only structure consulted when finding tags:

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

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

The .register_namespace() function is only useful for when serializing a tree out to text again.

这篇关于elementtree注册名称空间错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆