python-3.x - 在 Python 中使用解码进行 XML 解析
问题描述
我试图阅读的 XML 文件以 b' 开头。
不知道如何处理解码问题?
解决方案
所以你可以试试这个,但这会返回一个元素实例
import ast
import xml.etree.ElementTree as etree
tree = None
with open("property.xml", "r") as xml_file:
f = xml_file.read()
# convert string representation of bytes back to bytes
raw_xml_bytes= ast.literal_eval(f)
# read XML from raw bytes
tree = etree.fromstring(raw_xml_bytes)
另一种方法是读取文件并将其完全转换为字符串文件,然后再次重新读取,这将返回一个 ElementTree 实例。您可以使用以下方法实现此目的:
tree = None
with open("property.xml", "r") as xml_file:
f = xml_file.read()
# convert string representation of bytes back to bytes
raw_xml_bytes= ast.literal_eval(f)
# save the converted string version of the XML file
with open('output.xml', 'w') as file_obj:
file_obj.write(raw_xml_bytes.decode())
# read saved XML file
with open('output.xml', 'r') as xml_file:
tree = etree.parse(f)
推荐阅读
- ruby-on-rails - Rails 设计调用 POST 而不是 PUT 重置密码
- scala - 通用“嵌套成员”特征
- reactjs - 使用反应钩子设置状态,在什么情况下我必须传递一个函数来设置状态?
- python - 具有条件概率的随机选择
- javascript - 嵌套在 JSON 响应中的值未被解析
- azure - 在 HPC Pack 2016 中添加工作站节点
- angular - 如何将内容从子路由中的角度组件投影到父组件中的插槽?
- unity3d - 是否可以创建将动画文件保存为 Unity 3D 中的资产的游戏场景?
- swift - 快速错误:使用未解析的标识符“authData”
- python - 在 Python 中以对数方式缩放二维数组