[英]How should I deal with an XMLSyntaxError in Python's lxml while parsing a large XML file?
[英]Python lxml: how to deal with encoding errors parsing xml strings?
我在解析 xml 數據方面需要幫助。 這是場景:
encoded_string = bytes(bytearray(xml_data, encoding='utf-8'))
root = etree.fromstring(encoded_string)
當它不起作用時,我會收到兩種類型的錯誤消息:
"Extra content at the end of the document, line 1, column x (<string>, line 1)"
# x varies with string; I think it corresponds to the last character in the line
查看引發異常的行,看起來額外內容錯誤是由具有windows-1252編碼的文件引發的。
我需要能夠解析每個字符串,理想情況下無需在下載后以任何方式更改它們。 我嘗試了以下方法:
etree.fromstring
進行轉換最后一次嘗試產生了這個錯誤: ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
我能做些什么? 我需要能夠讀取這些字符串,但不知道如何解析它們。 使用 windows 編碼的 xml 字符串都以<?xml version="1.0" encoding="windows-1252"?>
開頭
given that the table column is text, all the XML content is being presented to python in UTF-8, as a result attempting to parse a conflicting XML encoding attribute will cause problems.
也許嘗試從字符串中剝離該屬性。
我通過刪除編碼信息、換行文字和回車文字解決了這個問題。 如果我在 vim 中打開返回錯誤的文件並運行以下三個命令,則每個字符串都被成功解析:
:%s/\\r//g
:%s/\\n//g
:%s/<?.*?>//g
然后 lxml 解析字符串沒有問題。
更新:
我有更好的解決方案。 問題是我正在復制到文本文件的 UTF-8 編碼字符串中的 \n 和 \r 文字。 我只需要使用regexp_replace
從字符串中刪除這些字符,如下所示:
select regexp_replace(xmlcolumn, '\\n|\\r', '', 'g') from table;
現在我可以運行以下命令並使用 lxml 讀取數據而無需進一步處理:
psql -d database -c "copy (select regexp_replace(xml_column, '\\n|\\r', '', 'g') from resource ) to stdout" > output.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.