【问题标题】:ElementTree XML parsing from UTF-8 source file从 UTF-8 源文件解析 ElementTree XML
【发布时间】:2017-01-16 04:16:03
【问题描述】:

我有这个 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>

【问题讨论】:

    标签: python xml parsing utf-8


    【解决方案1】:

    'proba.xml'.encode('utf8') 将字符串 'proba.xml' 编码为 UTF-8。它对同名文件没有任何作用。

    当文件真的被编码为 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

    【讨论】:

      猜你喜欢
      • 2013-07-14
      • 2010-11-11
      • 2012-11-07
      • 2020-01-20
      • 2015-11-18
      • 1970-01-01
      • 2023-03-25
      • 2012-04-20
      • 1970-01-01
      相关资源
      最近更新 更多