ExpatError:文档元素xml python错误之后的垃圾

时间:2016-11-02 03:08:41

标签: python xml

我有一个项目需要在python中从xml转换为dict。我正在使用xmltodict库但是当我将xml转换为dict时会引发错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/lib/python2.7/site-packages/xmltodict.py", line 311, in parse
    parser.Parse(xml_input, True)
ExpatError: junk after document element: line 2, column 0

我的代码是:

import xmltodict

xml = '<row dataType="TR" ID="3B6B408870BA7AC3E05381010A0A5849" agentCode="690001001001001" transferId="G87_AGIN160901115820S441XB" tradeNo="160831287638239" platformType="AGIN" playerName="mubuuvu2" transferType="IN" transferAmount="28" previousAmount="0" currentAmount="28" currency="CNY" exchangeRate="1" IP="0" flag="0" creationTime="2016-08-31 23:58:16" gameCode="" />\r\n<row dataType="TR" ID="3B6B408870BB7AC3E05381010A0A5849" agentCode="690001001001001" transferId="160831231227456_Hunter_Out" tradeNo="160831287639025" platformType="AGIN" playerName="zxh123" transferType="OUT" transferAmount="-50" previousAmount="50" currentAmount="0" currency="CNY" exchangeRate="1" IP="0" flag="0" creationTime="2016-08-31 23:58:18" gameCode="" />\r\n<row dataType="TR" ID="3B6B408870BC7AC3E05381010A0A5849" agentCode="690001001001001" transferId="160831231227452_Hunter_In" tradeNo="160831287639507" platformType="AGIN" playerName="qqq19qq32b" transferType="IN" transferAmount="71" previousAmount="0" currentAmount="71" currency="CNY" exchangeRate="1" IP="0" flag="0" creationTime="2016-08-31 23:58:19" gameCode="" />\r\n'

_dict = xmltodict.parse(xml, attr_prefix="")

我似乎无法找到解决问题的方法,而且我没有在xml中使用过,我与JSON一起使用

1 个答案:

答案 0 :(得分:3)

如果在开头添加一个起始根标记,在xml字符串的末尾添加一个结束根标记,它应该可以工作。

    import xmltodict

    xml = 'xml string here'
    xml = '<root>'+xml+'</root>'
    _dict = xmltodict.parse(xml, attr_prefix="")

基本上,它只是缺少<root>标记。