我如何解析python中的字符串并将其作为xml写入新的xml文件?

Ans*_*hul 10 python xml

我有字符串格式的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>"
Run Code Online (Sandbox Code Playgroud)

我想通过python将这些数据保存到一个新的xml文件中.

我正在使用此代码:

from xml.etree import ElementTree as ET
tree = ET.XML(xml_data)
Run Code Online (Sandbox Code Playgroud)

现在,我想创建一个xml文件并将xml树保存到文件中,但不知道要使用哪个函数.

谢谢

Ant*_*tti 14

ET.tostring(tree)您获得XML的非格式化字符串表示形式.要将其保存到文件:

with open("filename", "w") as f:
    f.write(ET.tostring(tree))
Run Code Online (Sandbox Code Playgroud)

  • 也许最好写成:`with open("filename.xml", "wb") as f: f.write(ET.tostring(tree))` (2认同)

Emn*_*oua 5

在 python 3.x 中建议的解决方案将不起作用,除非您指定with open("filename", "wb") as f:而不是with open("filename", "w") as f: