所以我有了这段代码,它(没有安装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发布于 2018-12-22 16:54:09
正如@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>https://stackoverflow.com/questions/53888803
复制相似问题