2013-01-02 9 views
6

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 

結果:OK動作します。

名前空間を一度に登録する機会はありますか?次に、listInvoice.find( '.// {http://www.stormware.cz/schema/version_2/invoice.xsd} id')の代わりにlistInvoice.find( 'inv:id')。textを使用したいと思います。 .text(より読みやすいコード)

+0

この回答はあなたのものによく似ています。http://stackoverflow.com/a/12861866/735204 –

答えて

14

名前空間の使用方法や.findall()のマニュアルが更新されていないようです。

.findall()関数(ならびに.find().findtext() and .iterfind()のマッピングであると考えられる) takes a namespaces`引数はすなわち、タグ見つけるとき相談だけの構造である:。

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

.register_namespace()機能をテキストを再度シリアル化するときにのみ役に立ちます。

+0

ありがとう、これは機能します!接頭辞 '{namespace-URL}'が必要です。 。 'element.get({{{http://www.w3.org/1999/02/22-rd--syntax-ns#} ID)'です。 –

+1

@Vincent:はい、属性アクセスは名前空間接頭辞変換をサポートしていないため、完全修飾名前空間接頭辞を渡す必要があります。 –

関連する問題