У меня есть XML-файлы с простой структурой:
<?xml version="1.0" encoding="iso-8859-1"?>
<DICTIONARY>
<Tag1>
Übung1 Übersetzung1
Übung2 Übersetzung2
Übung3 Übersetzung3
Übung4 Übersetzung4
Übung5 Übersetzung5
</Tag1>
<Tag2>
Übung6 Übersetzung6
Übung7 Übersetzung7
Übung8 Übersetzung8
Übung9 Übersetzung9
Übung10 Übersetzung10
</Tag2>
</DICTIONARY>
Я хотел прочитать эти файлы с помощью lxml из-за его простоты.Я использовал child.text для чтения частей текста, но, похоже, кодировка не передается в выходную строку.См. Код и вывод ниже.
Я уже использовал кодеки для чтения файла с iso-8859-1, но это ничего не изменило.
from lxml import etree
import codecs
def read_xml():
taglist=[]
new_dicts=[]
with codecs.open("A:/test/test.txt", 'r',
encoding='iso-8859-1') as xmlfile:
try:
tree=etree.parse(xmlfile)
loaded=True
print ("XML-encoding: ",tree.docinfo.encoding)
except:
loaded=False
print ("""No dictionary loaded or xml structure is missing! Please try again!""")
if loaded:
root = tree.getroot()
for child in root:
new_dict={}
tagname=child.tag
taglist.append(tagname)
print ("Loading dictionary for tag: ",
tagname)
allstrings= child.text
allstrings=allstrings.split("\n")
for line in allstrings:
if line!=" " and line!="":
line=line.split("\t")
if line[0]!="" and line[1]!="":
enc_line0=line[0]
enc_line1=line[1]
new_dict.update({enc_line0:enc_line1})
new_dicts.append(new_dict)
return taglist, new_dicts
print (read_xml())
Вывод:
XML-encoding: iso-8859-1
Loading dictionary for tag: Tag1
Loading dictionary for tag: Tag2
(['Tag1', 'Tag2'], [{'Ã\x9cbung1': 'Ã\x9cbersetzung1', 'Ã\x9cbung2': 'Ã\x9cbersetzung2', 'Ã\x9cbung3': 'Ã\x9cbersetzung3', 'Ã\x9cbung4': 'Ã\x9cbersetzung4', 'Ã\x9cbung5': 'Ã\x9cbersetzung5'}, {'Ã\x9cbung6': 'Ã\x9cbersetzung6', 'Ã\x9cbung7': 'Ã\x9cbersetzung7', 'Ã\x9cbung8': 'Ã\x9cbersetzung8', 'Ã\x9cbung9': 'Ã\x9cbersetzung9', 'Ã\x9cbung10': 'Ã\x9cbersetzung10'}])
Принимая во внимание, что я ожидал получить вывод таким же образом, как, например, с командой print ("Übung").Что я не прав?