2016-09-08 8 views
0

私はutf-8エンコーディングでこのXMLファイルを持っています。ElementTree UTF-8ソースファイルからのXMLの解析

<?xml version="1.0" encoding="UTF-8"?> 
<Items> 
<Item> 
<Cikkszam>00008</Cikkszam> 
<EAN/> 
<Megjegyzes>BISK</Megjegyzes> 
<Leiras1>Bisk Ontario, Dakota szappantartóhoz</Leiras1> 
<Leiras2>műanyag betét</Leiras2> 
<CikkTipus>07 </CikkTipus> 
<ME_>db </ME_> 
<Tipus>Választható</Tipus> 
<A_ar>338</A_ar> 
<B_ar>0</B_ar> 
<C_ar>0</C_ar> 
<D_ar>0</D_ar> 
<E_ar>0</E_ar> 
<Tenyl_keszl_>0</Tenyl_keszl_> 
<Visszaig_>0</Visszaig_> 
<Diszponalt>0</Diszponalt> 
<Szabad_keszlet>0</Szabad_keszlet> 
</Item> 
</Items> 

私はこのPythonコードを持っている:私は私のスクリプトファイルを実行すると

from xml.etree.ElementTree import ElementTree 
#import xml.etree.ElementTree 

items = ElementTree().parse('proba.xml'.encode('utf8')) 
#items = xml.etree.ElementTree.parse('proba.xml') 

products = items.findall("Item") 
for product in products: 
    print product.find("Leiras1").text 

私は次のエラーメッセージを得た:

C:\Python27>python read_xml_orig.py 
Bisk Ontario, Dakota szappantartóhoz 
Bisk Álló Wc kefe és papír tartó talpas 
Bisk sarok szappantartó króm 
Bisk sarok szappantartó króm 
Bisk üveg pohár pót 
Bisk ONTARIO üveg folyékony 
Bisk ONTARIO üveg polc 
Bisk ONTARIO dupla 
Bisk ONTARIO rud 
Traceback (most recent call last): 
    File "read_xml_orig.py", line 7, in <module> 
    print product.find("Leiras1").text 
    File "C:\Python27\lib\encodings\cp850.py", line 12, in encode 
    return codecs.charmap_encode(input,errors,encoding_map) 
UnicodeEncodeError: 'charmap' codec can't encode character u'\u0151' in position 
21: character maps to <undefined> 

答えて

0

'proba.xml'.encode('utf8')は、UTF-8などの文字列'proba.xml'を符号化します。同じ名前のファイルには何もしません。

ファイルが実際にUTF-8としてエンコードされている場合、あなたのコードは動作します:

私のためにこれを印刷し
from xml.etree.ElementTree import ElementTree 

doc = ElementTree().parse('proba.xml') 

products = doc.findall("Item") 
for product in products: 
    print product.find("Leiras1").text 

Bisk Ontario, Dakota szappantartóhoz 

しかし、あなたのファイルが実際にUTFではない場合-8の場合、.parse()の間にエンコードエラーが発生する可能性があります。

この場合、ファイルのエンコーディングを把握し、それに応じてXML宣言を修正する必要があります。ヒント:ハンガリー語の可能性のあるエンコード候補はWindows-1250です。

関連する問題