python - 从 Unicode 字符串创建 xml 节点(不支持编码声明)?

标签 python xml unicode lxml

我有一个数据库字段,它将 XML 文档存储为 Unicode。但是,当我获取该字段并尝试启动一个 lxml 节点时,出现以下错误:

node = etree.fromstring(self.xml)
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

我当前的文本 (self.xml) 包含日语字符等。我将如何创建节点?

最佳答案

如果你有unicode,你可以为lxml指定utf-8解析器:

utf8_parser = etree.XMLParser(encoding='utf-8')
node = etree.fromstring(self.xml.encode('utf-8'), parser=utf8_parser)

关于python - 从 Unicode 字符串创建 xml 节点(不支持编码声明)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31714503/

相关文章:

python - 如何使用包含 unicode 的值打印容器对象?

python - 如何使用 'selector gadget' 将数据抓取到 R 中?

python - TensorFlow Iris load_csv_with_header( )

python - 交互式 Jupyter 小部件在 Jupyter Lab 中不起作用

ANDROID 渲染问题 Null Exception

c++ - 添加 XML 元素和属性

android - 从另一个 View 更改 TextView 文本

c++ - 反转非 ASCII 字符的字符串

objective-c - 来自 Unicode 的 NSString

python - 使用 API 时使用 Python Fabric 与主机断开连接