【问题标题】:ExpatError: junk after document elementExpatError:文档元素后出现垃圾
【发布时间】:2011-10-07 21:50:21
【问题描述】:

我真的不知道,问题是什么?我收到以下错误:

File "C:\Python27\lib\xml\dom\expatbuilder.py", line 223, in parseString
parser.Parse(string, True)
ExpatError: junk after document element: line 5, column 0

我没有看到任何垃圾!有什么帮助吗?我快疯了……

text = """<questionaire>
<question>
    <questiontext>Question1</questiontext>
    <answer>Your Answer: 99</answer>
</question>
<question>
    <questiontext>Question2</questiontext>
    <answer>Your Answer: 64</answer>
</question>
<question>
    <questiontext>Question3</questiontext>
    <answer>Your Answer: 46</answer>
</question>
<question>
    <questiontext>Bitte geben</questiontext>
    <answer>Your Answer: 544</answer>
    <answer>Your Answer: 943</answer>
</question>
</questionaire>"""

cleandata = text.split('<questionaire>')
cleandatastring= "".join(cleandata)
stripped = cleandatastring.strip()
planhtml = stripped.split('</questionaire>')[0]
clean= planhtml.strip()


from xml.dom import minidom

doc = minidom.parseString(clean)
for question in doc.getElementsByTagName('question'):
    for answer in question.getElementsByTagName('answer'):
        if answer.childNodes[0].nodeValue.strip() == 'Your Answer: 99':
            question.parentNode.removeChild(question)

print doc.toxml() 

谢谢!

【问题讨论】:

  • 不要删除questionaire标签!

标签: python html-parsing minidom


【解决方案1】:

您原来的text 字符串是格式良好的XML。然后你做了一堆破坏它的东西。解析你原来的text,你会没事的。

XML 必须只有一个顶级元素。当你解析它时,它有许多顶级的&lt;question&gt; 标签。 XML 解析器将第一个元素解析为根元素,然后惊讶地发现另一个顶级元素。

【讨论】:

  • 谢谢...你能推荐一个关于解析html和xml的好介绍吗?
【解决方案2】:

在我的情况下,这是由于libxml2-2.9.11 中所做的更改导致tostring() (lxml) 返回的内容(元素后面的内容)超出了应有的范围。例如

from lxml import etree

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<a>
  <b>
  </b>
</a>
'''
t = etree.fromstring(xml.encode()).getroottree()
print(etree.tostring(
  t.xpath('/a/b')[0],
  encoding=t.docinfo.encoding,
).decode())

预期输出:

<b>
  </b>

实际输出:

<b>
  </b>
</a>

如果你将结果传递给xml.dom.minidom.parseString(),它会抱怨。

更多信息here

为避免这种情况,您要么需要 libxml2 &lt;= 2.9.10,要么需要 Alpine Linux >= 3.14。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2013-01-22
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多