python - 外派错误 : junk after document element

标签 python html-parsing minidom

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

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() 

谢谢!

最佳答案

你原来的text字符串是格式正确的 XML。然后你对它做了一堆破坏它的事情。解析你原来的text ,你会没事的。

XML 必须只有一个顶级元素。当你解析它时,它有许多顶级 <question>标签。 XML 解析器正在将第一个元素作为根元素进行解析,然后惊讶地发现另一个顶级元素。

关于python - 外派错误 : junk after document element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7693204/

相关文章:

python - 使用python从网页下载图片

python - 如何在 python 中生成另一个进程并捕获输出?

python错误: urlopen error [Errno 11001] getaddrinfo failed

python - 机器人框架: Using faker to generate a prefix string for account data

python - xgb.train 和 xgb.XGBRegressor(或 xgb.XGBClassifier)有什么区别?

java - 获取网页内容 - 浏览器不支持框架

java - 为什么 Swing Parser 的 handleText 不处理嵌套标签?

Python xml 迷你。生成 <text>Some text</text> 元素

Python 循环遍历 XML 中的元素并获取子元素值

python - XML:如何通过属性值获取元素 - Python 2.7 和 minidom