用漂亮的汤写xml
这可能是一个真正愚蠢的问题,但我还没有轻易找到答案。 一旦我根据需要修改了 xml 树,如何将其写回文件?
代码:
workbook = open("C:\\Users\\rabdel.WINCMPT\\Documents\\Retail Footwear.twb")
soup = BeautifulSoup(workbook)
for dashboard in soup.findAll("dashboard"):
print dashboard["name"]
if dashboard["name"] == "S1":
dashboard.extract()
for window in soup.findAll("window"):
print "class:",window["class"]
if "name" in [x[0] for x in window.attrs]:
print "name:",window["name"]
if window["name"] == "S1":
window.extract()
this may be a truly stupid question but I haven't readily found the answer.
once i modify the xml tree as necessary, how do I write it back out to file?
code:
workbook = open("C:\\Users\\rabdel.WINCMPT\\Documents\\Retail Footwear.twb")
soup = BeautifulSoup(workbook)
for dashboard in soup.findAll("dashboard"):
print dashboard["name"]
if dashboard["name"] == "S1":
dashboard.extract()
for window in soup.findAll("window"):
print "class:",window["class"]
if "name" in [x[0] for x in window.attrs]:
print "name:",window["name"]
if window["name"] == "S1":
window.extract()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法,获取字符串输出并写入文件:
Simplest way, get the output as a string and write to file:
从文档: 您可以将 Beautiful Soup 文档(或任何子集) )使用
str
函数或prettify
或renderContents
方法将其转换为字符串。您还可以使用unicode
函数以 Unicode 字符串形式获取整个文档。然后将该字符串写入文件,就像写入任何其他字符串一样。
From the docs: you can turn a Beautiful Soup document (or any subset of it) into a string with the
str
function, or theprettify
orrenderContents
methods. You can also use theunicode
function to get the whole document as a Unicode string.Then just write that string to a file as you would any other string.