【发布时间】:2021-07-20 06:48:55
【问题描述】:
让我们使用与 ElemtTree 文档中相同的 XML,只是增加了复杂性。在顶层添加了<subdata>,并将<capital> 添加为<country> 的子级
<?xml version="1.0"?>
<data>
<subdata>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E" />
<neighbor name="Switzerland" direction="W" />
<capital>
<name>Vaduz</name>
<anno>1860</anno>
</capital>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N" />
<capital>
<name>Singapore</name>
<anno>1836</anno>
</capital>
</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" />
<capital>
<name>Panama City</name>
<anno>1530</anno>
</capital>
</country>
</subdata>
</data>
我要做的是删除所有<capital> 元素及其子元素和数据。删除完成后,我想保存新的 XML 文件。我未能成功删除 <capital>
import xml.etree.ElementTree as ET
tree = ET.parse('country.xml')
root = tree.getroot()
capital = root.findall('.//capital')
for capital in root.findall('..//capital'):
root.remove(capital)
tree.write('countryOutput.xml')
我尝试了不同的方法将 xpath 写入大写元素,但到目前为止没有运气(技能)。
我的预期输出应该是这样的:
<?xml version="1.0"?>
<data>
<subdata>
<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>
</subdata>
</data>
【问题讨论】:
-
你的目标是用一个空的
subdata元素结束吗? -
不,我的目标是删除
capital元素。其余数据应保持不变。 -
我认为您应该编辑问题并向我们展示所需的确切输出。
-
所以你实际上想删除
<capital>元素,对吧?您确实写了“我要做的是删除所有<country>元素及其子元素和数据”,这让我感到困惑。 -
是的,我实际上想删除
capital。抱歉发错了。
标签: python xml xpath elementtree