【问题标题】:How do i parse a string in python and write it as an xml to a new xml file?如何在 python 中解析字符串并将其作为 xml 写入新的 xml 文件?
【发布时间】:2018-06-04 18:22:58
【问题描述】:

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

谢谢

【问题讨论】:

  • 如果你只是想把它写到一个文件中,你为什么要首先解析它?为什么不简单地open("file", "w").write(xml_data)
  • 你当场抓住了我.......谢谢

标签: python xml


【解决方案1】:

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

with open("filename", "w") as f:
    f.write(ET.tostring(tree))

【讨论】:

  • 也许最好写成:with open("filename.xml", "wb") as f: f.write(ET.tostring(tree))
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多