【问题标题】:Python: Update XML-file Using ElementTree While Keeping Namespace LabelsPython:在保留命名空间标签的同时使用 ElementTree 更新 XML 文件
【发布时间】:2015-10-23 14:03:48
【问题描述】:

我正在使用ElementTree 从 XML 中删除一些元素,然后将其写回。

写入文件后,命名空间的标签都已更改。

因此,使用 XML 的应用程序不再接受更新后的文件。

可以告诉ElementTree保留原来的标签吗?

例如。这是源 XML 的一部分:

<gnc:account version="2.0.0">
  <act:name>Root Account</act:name>
  <act:id type="guid">9f8f1286bffd64d6dff54385a62b2650</act:id>
  <act:type>ROOT</act:type>
  <act:commodity>
    <cmdty:space>ISO4217</cmdty:space>
    <cmdty:id>NZD</cmdty:id>
  </act:commodity>
  <act:commodity-scu>100</act:commodity-scu>
</gnc:account>

写回来后:

<ns0:account version="2.0.0">
  <ns5:name>Root Account</ns5:name>
  <ns5:id type="guid">9f8f1286bffd64d6dff54385a62b2650</ns5:id>
  <ns5:type>ROOT</ns5:type>
  <ns5:commodity>
    <ns4:space>ISO4217</ns4:space>
    <ns4:id>NZD</ns4:id>
  </ns5:commodity>
  <ns5:commodity-scu>100</ns5:commodity-scu>
</ns0:account>

我使用的python代码是:

import xml.etree.ElementTree as ET

tree = ET.parse('file1.xml')
root = tree.getroot()
tree.write('file2.xml')

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    切换到lxml 使其工作:

    import lxml.etree as ET
    
    tree = ET.parse(args.infile)
    root = tree.getroot()
    tree.write(args.outfile,
               xml_declaration=True,encoding='utf-8',
               method="xml")
    

    现在的输出是:

    <gnc:account version="2.0.0">
      <act:name>Root Account</act:name>
      <act:id type="guid">9f8f1286bffd64d6dff54385a62b2650</act:id>
      <act:type>ROOT</act:type>
      <act:commodity>
        <cmdty:space>ISO4217</cmdty:space>
        <cmdty:id>NZD</cmdty:id>
      </act:commodity>
      <act:commodity-scu>100</act:commodity-scu>
    </gnc:account>
    

    ...与输入完全相同。

    【讨论】:

      猜你喜欢
      • 2016-12-04
      • 2012-03-23
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2014-09-24
      • 1970-01-01
      相关资源
      最近更新 更多