python - 添加节点后将 XML 树漂亮打印到文件
问题描述
我看过几篇关于在解析后漂亮地打印整个 XMl 的解决方案的建议。就我而言,我在原始文件中添加了一个新节点,将结果打印到一个新文件中。我如何保持与原始节点相同的缩进。
原始文件:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
添加新country
节点的代码:
file_path = "xmlsample1.xml"
tree = ET.parse(file_path)
root = tree.getroot()
new_country = ET.SubElement(root, 'country')
new_rank = ET.SubElement(new_country, 'rank')
new_rank.text = '120'
tree.write('output.xml')
这是看起来的output.xml
样子:
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E" />
<neighbor name="Switzerland" direction="W" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N" />
</country>
<country name="Panama">
<rank updated="yes">100</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W" />
<neighbor name="Colombia" direction="E" />
</country>
<country><rank>120</rank></country></data>
如何使它看起来像这样(即country
遵循相同级别的缩进):
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E" />
<neighbor name="Switzerland" direction="W" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N" />
</country>
<country name="Panama">
<rank updated="yes">100</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W" />
<neighbor name="Colombia" direction="E" />
</country>
<country>
<rank>120</rank>
</country>
</data>
解决方案
推荐阅读
- c++ - Android Studio 问题中的 Java 错误现已解决
- android - 使用自定义可绘制对象更改操作栏向上指示器后,将其更改为默认的后退箭头按钮
- r - 在以下两种情况下放置 if 语句的最佳方式是什么?
- kubernetes - 一个 K8s POD 是如何实现的,它的核心实现组件是什么?
- shell - 如何在特定路径中运行 shell 命令
- google-apps-script - Google 应用脚本 - 为什么我的 onEdit() 函数需要这么长时间?
- postgresql - 我可以在热备副本上使用临时表的替代方法吗?
- google-maps-api-3 - 为具有相同位置的标记聚类器显示信息窗口
- python - 当一个列表的所有元素都在另一个列表中时如何分组和求和
- css - 如何修复不透明度 0 并使用 aos.js 在移动设备上进行转换?