【问题标题】:ElementTree : insert method and bad indentation outputElementTree:插入方法和错误的缩进输出
【发布时间】:2020-09-15 16:20:45
【问题描述】:

我使用此代码在原始 .xml(取自 ElementTree 文档的文件)中插入一个新节点:

import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()


my_xml = """
    <country name="Togo">
        <rank updated="yes">2</rank>
        <year>2000</year>
        <gdppc>3</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
"""


new_contry = ET.fromstring(my_xml)
root.insert(1,new_contry)

tree.write('essai_insert_output.xml')

root = tree.getroot()

但是结果破坏了新节点和下一个节点之间的正确缩进:

<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E" />
        <neighbor name="Switzerland" direction="W" />
    </country>
    <country name="Togo">
        <rank updated="yes">2</rank>
        <year>2000</year>
        <gdppc>3</gdppc>
        <neighbor name="Austria" direction="E" />
        <neighbor name="Switzerland" direction="W" />
    </country><country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N" />
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W" />
        <neighbor name="Colombia" direction="E" />
    </country>
</data>

新节点&lt;country name="Togo"&gt;放置得很好,但在它的最后,我们有这个冲突:

</country><country name="Singapore">

如何治疗这种影响?

【问题讨论】:

  • 只是格式问题。结构是对的。
  • @dabingsou 好的,但是如何改进格式?我必须为某人转换 XML 文件,重点是提供格式良好的 XML 输出(我尝试了 lxml 模块,但遇到了同样的问题)。
  • 这里是一个格式化输出的例子。
  • 您可以通过在new_contry 元素的tail 中添加一些空格来使输出看起来更漂亮。像这样:new_contry.tail = "\n ".
  • 以下是使用 lxml 获得漂亮打印输出的方法:stackoverflow.com/q/42577999/407651

标签: python insert indentation elementtree pretty-print


【解决方案1】:

格式化输出。

from xml.dom import minidom

dom = minidom.parse('country_data.xml')
with open('dom_write.xml', 'w', encoding='UTF-8') as fh:
    dom.writexml(fh, indent='', addindent='\t', newl='', encoding='UTF-8')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 2021-09-06
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多