【问题标题】:lxml.etree.XMLSyntaxError, Document labelled UTF-16 but has UTF-8 contentlxml.etree.XMLSyntaxError,文档标记为 UTF-16 但具有 UTF-8 内容
【发布时间】:2018-10-12 14:52:07
【问题描述】:

lxml.etree.XMLSyntaxError,文档标记为 UTF-16 但包含 UTF-8 内容

我在 python 中使用 lxml lib 时遇到错误。其他解决方案/黑客正在将文件 php.ini 中的 utf-16 替换为 utf-8。解决这个问题的pythonic方法是什么?

python 代码:

import lxml.etree as etree

tree =  etree.parse("req.xml")

req.xml:

<?xml version="1.0" encoding="utf-16"?>
<test 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
</test>

【问题讨论】:

  • 你想要输出什么?
  • 我只需要解析那个xml,编码不重要

标签: python xml utf-8 lxml utf-16


【解决方案1】:

您可以使用 BeautifulSoup 解析 xml 内容,这是您需要的更 Python 的方式。

注意:如果您的数据以utf-16 编码,则可以在读取/解析文件内容期间通过在utf-8 中解码轻松解析。

所以下面是代码:

sample.xml 包含以下数据:

<?xml version="1.0" encoding="utf-16"?>
<test 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
</test>

代码:

from bs4 import BeautifulSoup
with open("sample.xml", "r") as f: # opening xml file
    content = f.read().decode('utf-8', 'ignore') # xml content stored in this variable and decode to utf-8

soup = BeautifulSoup(content, 'html.parser') #parse content to BeautifulSoup Module
data = [data.attrsfor data in soup.findAll("test")]
print data

输出:

{u'xmlns:xsi': u'http://www.w3.org/2001/XMLSchema-instance', u'xmlns:xsd': u'http://www.w3.org/2001/XMLSchema'}

【讨论】:

  • 但是...将文件读取到内存并将解码的字符串传递给解析也适用于lxml(使用etree.fromstring())。在这里使用 HTML 解析器解析 XML 有什么好处?
  • 感谢您的回答,但这可以像 lenz 所说的那样在 lxml 中实现。无需使用另一个库进行字符串解码。
  • @lenz 是的,我完全同意您的回答,但这只是另一种方法。这就是为什么我在NOTE 中提到你必须在解析时解码(UTF-8)内容,我通常说的是你使用的任何包
  • 我还是不明白你为什么推荐使用 HTML 解析器。我的意思是,即使是 BS 也有一个 XML 解析器:soup = BeautifulSoup(content, 'xml') 将是一种与使用不同库的 OP 相同的方式。但是为什么你明确建议使用'html.parser'
  • @lenz 我不建议使用beautifulsoup,这只是一种方法。
【解决方案2】:

查看XMLParser 构造函数的文档:

>>> help(etree.XMLParser)

在其他选项中,有一个 encoding 参数,如文档所述,它允许您“覆盖文档编码”。

这正是你需要的:

parser = etree.XMLParser(encoding='UTF-8')
tree = etree.parse("req.xml", parser=parser)

如果错误消息是正确的(即文档没有任何其他问题),那么我希望它可以工作。

【讨论】:

    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多