您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将Python ElementTree转换为字符串

将Python ElementTree转换为字符串

Element对象没有.getroot()方法。挂断该电话,该.tostring()电话将正常工作:

xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')

.getroot()当有ElementTree实例时才需要使用。

其他说明:

这将产生一个 bytestring ,在Python 3中是该bytes类型。 如果必须有一个str对象,则有两个选择:

从UTF-8解码结果字节值: xmlstr.decode("utf8")

使用encoding='unicode'; 这样可以避免编码/解码周期:

    xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')

如果要使用UTF-8编码的字节串值或使用Python 2,请考虑到ElementTree不能正确检测utf8为标准XML编码,因此将添加一个<?xml version='1.0' encoding='utf8'?>声明。如果要防止这种情况,请使用utf-8UTF-8(带破折号)。使用时encoding="unicode"添加声明头。

python 2022/1/1 18:35:35 有232人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶