如何在python中解析字符串并将其作为xml写入新的xml文件?
我有字符串格式的xml数据,它是变量xml_数据如何在python中解析字符串并将其作为xml写入新的xml文件?,python,xml,Python,Xml,我有字符串格式的xml数据,它是变量xml_数据 xml_data="<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </no
xml_data="<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>"
现在,我想创建一个xml文件并将xml树保存到该文件中,但不知道使用哪个函数
感谢使用ET.tostring(tree)
可以获得XML的非格式化字符串表示形式。要将其保存到文件,请执行以下操作:
with open("filename", "w") as f:
f.write(ET.tostring(tree))
在Python3.x中
除非您将open(“filename”,“wb”)指定为f:而不是将open(“filename”,“w”)指定为f:,否则建议的解决方案将不起作用。如果您只想将其写入文件,为什么首先要对其进行解析?为什么不干脆
open(“file”,“w”).write(xml\U数据)
?你当场抓到了我…….谢谢你也许最好把open(“filename.xml”,“wb”)写成,而把open(“filename.xml”,“wb”)写成f:f.write(ET.tostring(tree))
with open("filename", "w") as f:
f.write(ET.tostring(tree))