我試圖用這個註冊命名空間: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(更好的代碼和易於閱讀)
這個答案看起來很像你的http://stackoverflow.com/a/12861866/735204 –