【问题标题】:Maintaining the indentation of an XML file when parsed with Beautifulsoup使用 Beautifulsoup 解析时保持 XML 文件的缩进
【发布时间】: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>

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

【问题讨论】:

标签: python xml beautifulsoup bs4


【解决方案1】:

很遗憾,您不能直接访问它。 Beautiful soup 解析其输入,并且不保留原始格式的痕迹。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2023-03-11
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多