Python elementtree寄存器命名空间错误
我尝试使用以下内容注册命名空间:Python elementtree寄存器命名空间错误,python,elementtree,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:invoi
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.:
结果:AttributeError:“元素”对象没有属性“nsmap”
3.:
结果:工作正常
是否有机会立即注册名称空间?然后我想使用listInvoice.find('inv:id').text而不是listInvoice.find(')//{http://www.stormware.cz/schema/version_2/invoice.xsd}id').text(更好的代码和易于阅读)看起来文档还没有更新如何使用名称空间和
.findall()
.findall()
函数(以及.find()
、.findtext()和
.iterfind())接受一个
namespaces`参数,该参数应该是一个映射。这是查找标记时参考的唯一结构:
root.findall('inv:invoiceHeader', namespaces=dict(inv='http://www.stormware.cz/schema/version_2/invoice.xsd'))
.register\u namespace()
函数仅在将树重新序列化为文本时有用。此答案与您的答案非常相似,谢谢,这很有效!对于.get()
我需要使用{namespace URL}
作为前缀,例如element.get({http://www.w3.org/1999/02/22-rdf-syntax-ns#}ID)
@Vincent:是的,属性访问不支持名称空间前缀转换,您需要传入完全限定的名称空间前缀。
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
root.findall('inv:invoiceHeader', namespaces=dict(inv='http://www.stormware.cz/schema/version_2/invoice.xsd'))