'ParseError: not well-formed' XML 数据中某些特殊字符的错误



我有以下代码来清理日志文件,从中获取XML(日志文件格式不好,没有根(,然后解析并执行其他功能。清理是有效的,但XML解析器为一些包含一些特殊字符的XML数据抛出了错误。我的代码如下:

with open(log_file, 'r') as fr, open('XMLinLog2.xml', 'w') as fw:
fw.write("<document>n")
for line in fr:
if line.strip().startswith('<'):
fw.write('t' + line)
fw.write("n</document>")
# --- Parsing Log files after cleanup ---
doc = ET.parse('XMLinLog2.xml')

引发我错误的日志文件中的xml数据是for;(1(Ops Désactivée 23:59和(2([mono@90°>>+1在日志文件中清理后显示为操作D�sactiv�e 23:59[单声道@90� >gt+1。所以我发现�角色引发了问题。问题:

  1. 如何处理此错误
  2. 若我需要打印这些数据,我该如何正确打印?我不想打印�.因为我想每当我收到法语文本时,它都会出错

此处为完整错误:raceback(最后一次通话(:文件";C:/Users/PycharmProjects/IMSS_TestHarness/Libraries/try.py";,第23行,indoc=ET.parse('XMLinLog2.xml'(文件";C: \Users\AppData\Local\Programs\Python38-32\lib\xml\etree\ElementTree.py";,第1202行,在解析中tree.parse(源,解析器(文件";C: \Users\AppData\Local\Programs\Python38-32\lib\xml\etree\ElementTree.py";,第595行,在解析中自我_root=解析器_parse_whole(源(xml.etree.ElementTree.ParseError:格式不正确(无效标记(:第3299行,第22列

进程结束,退出代码为1

日志文件:

1.  2020-08-03 15:59:54.635 (72 ,Effective Commit) Info          Sending:
<U_DisplayCommand>
<DestinationId>5035</DestinationId>
<DisplayId>1</DisplayId>
<LineTextEnglish>
<Line>Ops Disabled 23:59 N</Line>
</LineTextEnglish>
<LineTextFrench>
**<Line>Ops Désactivée 23:59</Line>**
</LineTextFrench>
</U_DisplayCommand>
<U_DisplayCommand>
<DestinationId>5085</DestinationId>
<DisplayId>1</DisplayId>
<LineTextEnglish>
<Line>Vaudreuil-Dori P123A</Line>
<Line>[ mono @ 90° &gt;&gt; +1</Line>
</LineTextEnglish>
<LineTextFrench>
<Line>Vaudreuil-Dori P123A</Line>
<Line>[ mono @ 90° &gt;&gt; +1</Line>
</LineTextFrench>
</U_DisplayCommand>

提前谢谢。

实际上添加编码对我有效。

with open(log_file, 'r') as fr, open('XMLinLog2.xml', 'w', encoding='utf-8') as fw:
fw.write("<document>n")
for line in fr:
if line.strip().startswith('<'):
fw.write('t' + line)
fw.write("n</document>")
# --- Parsing Log files after cleanup ---
doc = ET.parse('XMLinLog2.xml')

最新更新