繁体   English   中英

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

[英]How do i parse a string in python and write it as an xml to a new xml file?

我有字符串格式的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树保存到文件中,但不知道要使用哪个函数。

谢谢

使用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:否则建议的解决方案将不起作用with open("filename", "w") as f:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM