首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有xmltodict unparse()函数的ValueError -Python3

带有xmltodict unparse()函数的ValueError -Python3
EN

Stack Overflow用户
提问于 2015-04-23 19:00:01
回答 2查看 5.4K关注 0票数 3

我在使用xmltodict将json转换为xml时遇到了困难。但是,当我试图转换多个对象时,它会返回一个ValueError "ValueError:“。

以下是我的JSON数据:

到目前为止,我的脚本如下:

代码语言:javascript
复制
import json
import xmltodict

    y = """{{  "markers":[  {  "point":"new GLatLng(40.266044,-74.718479)","awayTeam":"LUGip","markerImage":"images/red.png","fixture":"Wednesday 7pm","information":"Linux users group meets second Wednesday of each month.","previousScore":"","capacity":"","homeTeam":"Lawrence Library"},{  "point":"new GLatLng(40.211600,-74.695702)","awayTeam":"LUGip HW SIG","tv":"","markerImage":"images/white.png","fixture":"Tuesday 7pm","information":"Linux users can meet the first Tuesday of the month to work out harward and configuration issues.","capacity":"","homeTeam":"Hamilton Library"},{  "point":"new GLatLng(40.294535,-74.682012)","awayTeam":"After LUPip Mtg Spot","tv":"","markerImage":"images/newcastle.png","fixture":"Wednesday whenever","information":"Some of us go there after the main LUGip meeting, drink brews, and talk.","capacity":"2 to 4 pints","homeTeam":"Applebees"}]}"""

y2 = json.loads(y)
print(xmltodict.unparse(y2, pretty = True))

结果:

代码语言:javascript
复制
Traceback (most recent call last):

  File "<ipython-input-89-8838ce8b0d7f>", line 1, in <module>
    print(xmltodict.unparse(y2,pretty=True))

  File "/Users/luzazul/anaconda/lib/python3.4/site-packages/xmltodict.py", line 323, in unparse
    raise ValueError('Document must have exactly one root.')

ValueError: Document must have exactly one root.

任何帮助都将不胜感激,谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-24 22:54:33

假设您已经清理了输入以使其有效(请参阅对问题的评论)。

看起来,xmltodict试图为列表中的每个项创建一个markers元素,而且由于markers位于顶层,所以您试图创建多个根。

为此,我将在数据周围添加一个顶级元素,如下所示:

代码语言:javascript
复制
y2 = {'root':y2}
票数 3
EN

Stack Overflow用户

发布于 2015-09-20 07:56:44

您可以使用xmljson库来使用不同的XML约定进行转换。它通过返回元素数组来支持多个根。

例如:

代码语言:javascript
复制
>>> import xmljson
>>> xmljson.badgerfish.etree({'x': 1, 'y': 2})
[<Element y at 0x3114a08>, <Element x at 0x3114a48>]

--返回xy元素。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29832127

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档