【问题标题】:Read, Modify the xml save it in a new xml using python读取,修改xml使用python将其保存在新的xml中
【发布时间】:2018-09-25 13:55:15
【问题描述】:

以下是我正在遵循的步骤:

  1. 将 xml 文件作为字典读取

    import xmltodict
    
    with open("example.xml") as sxml:
        data = xmltodict.parse(sxml.read())
    
  2. 改变值

    data["key"]["key1"] = "some value"
    
  3. 我想将更改保存在 example.xml 文件中,或者我想创建一个新文件并保存更改。

我该怎么做?

【问题讨论】:

标签: python xml xmltodict dicttoxml


【解决方案1】:

按照README我们可以简单地做

with open('example.xml', 'w') as result_file:
    result_file.write(xmltodict.unparse(data))

如果你想覆盖 example.xml 或者

with open('result.xml', 'w') as result_file:
    result_file.write(xmltodict.unparse(data))

如果要创建新文件result.xml

【讨论】:

    【解决方案2】:

    简单回答:

    from lxml import etree
    readfile=open('yourxmlfile.xml','r')
    rstring = readfile.read()
    readfile.close()
    parser=etree.XMLParser(strip_cdata=False)
    tree = etree.XML(rstring,parser)
    root = tree
    #make some edits to root here
    wfile = open('yourxmlfileoutput.xml','w')
    wfile.write(etree.tostring(root))
    wfile.close()
    

    xml模块的文档可以在here找到

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2017-01-26
      • 2020-12-23
      • 2015-11-30
      相关资源
      最近更新 更多