使用其他功能时,已安装的lxml导致TypeError

时间:2018-12-21 17:36:50

标签: python python-3.x lxml

所以我有这段代码(未安装lxml)可以正常工作

from xml.etree.ElementTree import Element, tostring
from xmljson import badgerfish as bf

dic = {'p': {'@id': 'main'}}

output = bf.etree(dic, root=Element('root'))
print(tostring(output).decode('utf-8'))

输出为

<root><p id="main" /></root>

问题是我需要lxml来完成另一个任务,但是如果我通过pip install lxml安装它,则上面的代码会产生此错误

TypeError: append() argument must be xml.etree.ElementTree.Element, not lxml.etree._Element 

那么我如何在lxml中使用以上代码?

完整堆栈跟踪:

TypeError                                 Traceback (most recent call last)
<ipython-input-1-7478b75b9581> in <module>
      4 dic = {'p': {'@id': 'main'}}
      5 
----> 6 output = bf.etree(dic, root=Element('root'))
      7 print(tostring(output).decode('utf-8'))

~/.local/lib/python3.7/site-packages/xmljson/__init__.py in etree(self, data, root)
    132                     if elem is None:
    133                         continue
--> 134                     result.append(elem)
    135                     # Treat scalars as text content, not children (Parker)
    136                     if not isinstance(value, (self.dict, dict, self.list, list)):

TypeError: append() argument must be xml.etree.ElementTree.Element, not lxml.etree._Element

1 个答案:

答案 0 :(得分:0)

正如@jordanm所建议的,我必须将lxml元素传递给bf.etree()而不是xml.etree元素,因此工作代码是

from lxml.etree import Element as EElement
from xml.etree.ElementTree import Element, tostring
from xmljson import badgerfish as bf

dic = {'p': {'@id': 'main'}}

output = bf.etree(dic, root=EElement('root'))
print(tostring(output).decode('utf-8'))

产生正确的输出

<root><p id="main" /></root>