强制转换为Unicode:需要字符串或缓冲区,xml.etree._ElementTree找到

时间:2013-01-29 15:23:42

标签: python xml-parsing lxml

我是python的新手,我收到以下错误。

$ python testrun.py 
Traceback (most recent call last):
  File "testrun.py", line 13, in <module>
    with open(tree, 'w') as file_handle:
TypeError: coercing to Unicode: need string or buffer, lxml.etree._ElementTree found

使用此代码:

from lxml import etree
tree = etree.parse('testregression_config.xml')

for elem in tree.findall('.//xmpp'):
    #assert elem.attrib['name'] == 'test02'
    elem.attrib['name'] == 'test03'

for elem in tree.findall('.//xmpp-config'):
    #assert elem.text == 'QA'
    elem.text = 'Prod'

with open(tree, 'w') as file_handle:
    file_handle.write(etree.tostring(tree, pretty_print=True, encoding='utf8'))

<config>
  <logging/>
  <test-mode>false</test-mode>
  <test name="test02">
    <mail/>
    <test-system>0</test-system>
    <system id="0" name="suite1" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="1" name="suite2" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="2" name="suite3" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="3" name="suite4" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="4" name="suite5" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
  </test>
</config>

1 个答案:

答案 0 :(得分:1)

在这一行

with open(tree, 'w') as file_handle:

您正在传递lxml.etree._ElementTree对象作为文件名。您可能错过了引用并打算

with open('tree', 'w') as file_handle:

错误消息和回溯是不言自明的

错误位置with open(tree, 'w') as file_handle:因此它与open声明

有关

错误消息TypeError: coercing to Unicode: need string or buffer, lxml.etree._ElementTree found

所以我们似乎正在将lxml.etree._ElementTree而不是字符串传递给open。当然,我们正在这样做,我们传递的tree不是字符串而是tree = etree.parse('testregression_config.xml'),根据文件中的第二个语句