【问题标题】:Parse XML with Python with fewer lines使用 Python 解析 XML,行数更少
【发布时间】:2018-01-11 14:04:58
【问题描述】:
我在一些 Python 中使用 BS4 使原始字符串看起来像漂亮的 XML。
我正在使用这个:
fileText = (BeautifulSoup(fileText, "xml").prettify())
它给了我这样的输出:
<foobar>
<foo>
bar
</foo>
<foo>
bar2
</foo>
</foobar>
但我想:
<foobar>
<foo>bar</foo>
<foo>bar2</foo>
</foobar>
非常感谢任何帮助!
【问题讨论】:
标签:
python
xml-parsing
beautifulsoup
【解决方案1】:
来自Jayesh Bhoot's answer:
from lxml import etree, html
doc = html.fromstring(fileText)
print(etree.tostring(doc, encoding='unicode', pretty_print=True))
根据 dspjm 对上面链接的答案的评论,这同样有效:
print(html.tostring(doc, encoding='unicode', pretty_print=True, method='xml'))
唯一的条件是使用html.tostring时需要method='xml'。
输出:
<foobar>
<foo>bar</foo>
<foo>bar2</foo>
</foobar>