【发布时间】:2015-07-01 20:29:12
【问题描述】:
我正在使用 BS4 解析 XML 文件并尝试将其写回新的 XML 文件。
输入文件:
<tag1>
<tag2 attr1="a1"> example text </tag2>
<tag3>
<tag4 attr2="a2"> example text </tag4>
<tag5>
<tag6 attr3="a3"> example text </tag6>
</tag5>
</tag3>
</tag1>
脚本:
soup = BeautifulSoup(open("input.xml"), "xml")
f = open("output.xml", "w")
f.write(soup.encode(formatter='minimal'))
f.close()
输出:
<tag1>
<tag2 attr1="a1"> example text </tag2>
<tag3>
<tag4 attr2="a2"> example text </tag4>
<tag5>
<tag6 attr3="a3"> example text </tag6>
</tag5>
</tag3>
</tag1>
我想保留输入文件的缩进。我尝试使用美化选项。
输出美化:
<tag1>
<tag2 attr1="a1">
example text
</tag2>
<tag3>
<tag4 attr2="a2">
example text
</tag4>
<tag5>
<tag6 attr3="a3">
example text
</tag6>
</tag5>
</tag3>
</tag1>
但这不是我想要的。我想保持准确的缩进 输入文件中的标签。
【问题讨论】:
-
检查this question's的答案。
标签: python xml beautifulsoup bs4