使用 Beautifulsoup 解析 XML 文件时保持缩进 [英] Maintaining the indentation of an XML file when parsed with Beautifulsoup

查看:38
本文介绍了使用 Beautifulsoup 解析 XML 文件时保持缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 BS4 解析 XML 文件并尝试将其写回新的 XML 文件.

I am using BS4 to parse an XML file and trying to write it back to a new XML file.

输入文件:

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

我想保留输入文件的缩进.我尝试使用美化选项.

I want to retain the indentation of the input file. I tried using prettify option.

输出美化:

<tag1>
  <tag2 attr1="a1"> 
    example text 
  </tag2>
  <tag3>
    <tag4 attr2="a2"> 
      example text 
    </tag4>
    <tag5>
      <tag6 attr3="a3"> 
        example text 
      </tag6>
    </tag5>
   </tag3>
</tag1>

但这不是我想要的.我想保持精确的缩进输入文件中的标签.

But this is not what I wanted. I want to maintain the exact indentation of the tags as in the input file.

推荐答案

很遗憾你不能直接去它.Beautiful Soup 解析它的输入并且不保留原始格式的痕迹.

Unfortunately you cannot to it directly. Beautiful soup parses its input and keeps no trace of the original formatting.

因此,如果不修改 XML,您可以先在内存中将其作为整个字符串读取,然后将该字符串输入 BS 进行解析并进行测试,然后使用它写回新文件.

So, if do do not modify the XML, you could first read it as a whole string in memory, then feed that string into BS to parse it and make your tests, and then use it to write back to the new file.

如果您想修改 XML 并使用特殊格式,则必须导航 BS 树并手动格式化.

If you want to modify the XML and use a special formatting, you will have to navigate the BS tree and format it by hand.

这篇关于使用 Beautifulsoup 解析 XML 文件时保持缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆