我有字符串格式的xml数据,它在变量xml_data中
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>"
我想通过python将这些数据保存到一个新的xml文件中.
我正在使用此代码:
from xml.etree import ElementTree as ET
tree = ET.XML(xml_data)
现在,我想创建一个xml文件并将xml树保存到文件中,但不知道要使用哪个函数.
谢谢
Ant*_*tti 14
随ET.tostring(tree)您获得XML的非格式化字符串表示形式.要将其保存到文件:
with open("filename", "w") as f:
    f.write(ET.tostring(tree))
在 python 3.x 中建议的解决方案将不起作用,除非您指定with open("filename", "wb") as f:而不是with open("filename", "w") as f:
| 归档时间: | 
 | 
| 查看次数: | 13823 次 | 
| 最近记录: |