Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用Beautifulsoup解析时维护XML文件的缩进_Python_Xml_Beautifulsoup_Bs4 - Fatal编程技术网

Python 使用Beautifulsoup解析时维护XML文件的缩进

Python 使用Beautifulsoup解析时维护XML文件的缩进,python,xml,beautifulsoup,bs4,Python,Xml,Beautifulsoup,Bs4,我正在使用BS4解析XML文件,并尝试将其写回新的XML文件 输入文件: 示例文本 示例文本 示例文本 脚本: soup = BeautifulSoup(open("input.xml"), "xml") f = open("output.xml", "w") f.write(soup.encode(formatter='minimal')) f.close() 输出: soup = BeautifulSoup(open("input.xml"), "xml") f = open("ou

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

输入文件:


示例文本
示例文本
示例文本
脚本:

soup = BeautifulSoup(open("input.xml"), "xml")
f = open("output.xml", "w") 
f.write(soup.encode(formatter='minimal'))
f.close()
输出:

soup = BeautifulSoup(open("input.xml"), "xml")
f = open("output.xml", "w") 
f.write(soup.encode(formatter='minimal'))
f.close()

示例文本
示例文本
示例文本
我想保留输入文件的缩进。我试着使用美化选项

输出美化:

soup = BeautifulSoup(open("input.xml"), "xml")
f = open("output.xml", "w") 
f.write(soup.encode(formatter='minimal'))
f.close()

示例文本
示例文本
示例文本
但这不是我想要的。我想保持准确的缩进
输入文件中的所有标记。

很遗憾,您无法直接将其添加到。Beauty soup解析其输入,不保留原始格式的任何痕迹

因此,如果您不修改XML,您可以首先在内存中将其作为一个完整的字符串读取,然后将该字符串馈送到BS中进行解析和测试,然后使用它写回新文件

如果要修改XML并使用特殊格式,则必须导航BS树并手动设置格式。

检查答案。