将Python ElementTree转换为字符串

发布于 2021-01-29 18:17:47

每当我致电时ElementTree.tostring(e),都会收到以下错误消息:

AttributeError: 'Element' object has no attribute 'getroot'

还有其他方法可以将ElementTree对象转换为XML字符串吗?

追溯:

Traceback (most recent call last):
  File "Development/Python/REObjectSort/REObjectResolver.py", line 145, in <module>
    cm = integrateDataWithCsv(cm, csvm)
  File "Development/Python/REObjectSort/REObjectResolver.py", line 137, in integrateDataWithCsv
    xmlstr = ElementTree.tostring(et.getroot(),encoding='utf8',method='xml')
AttributeError: 'Element' object has no attribute 'getroot'
关注者
0
被浏览
46
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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

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

    其他说明:

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

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

      2. 使用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"不添加声明头。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看