Soviut对lxml objectify的建议是好的。通过一个特殊的子类simplejson,您可以将lxml objectify结果转换为json。import simplejson as json
import lxml
class objectJSONEncoder(json.JSONEncoder):
"""A specialized JSON encoder that can handle simple lxml objectify types
>>> from lxml import objectify
>>> obj = objectify.fromstring("1.50W. Shakespeare")
>>> objectJSONEncoder().encode(obj)
'{"price": 1.5, "author": "W. Shakespeare"}'
"""
def default(self,o):
if isinstance(o, lxml.objectify.IntElement):
return int(o)
if isinstance(o, lxml.objectify.NumberElement) or isinstance(o, lxml.objectify.FloatElement):
return float(o)
if isinstance(o, lxml.objectify.ObjectifiedDataElement):
return str(o)
if hasattr(o, '__dict__'):
#For objects with a __dict__, return the encoding of the __dict__
return o.__dict__
return json.JSONEncoder.default(self, o)
请参见docstring的用法示例,本质上是将lxmlobjectify的结果传递给objectJSONEncoder实例的encode方法
注意,Koen的观点在这里非常有效,上面的解决方案只适用于简单的嵌套xml,不包括根元素的名称。这是可以解决的。