Python XML 用 ElementTree 删除孙子和孙子

Python XML removing grandchildren and grandgrandchildren with ElementTree

让我们使用与 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>

获取所有 <country> 元素的列表。在每一个上,删除 <capital> 子元素。

import xml.etree.ElementTree as ET
 
tree = ET.parse('country.xml')
countries = tree.findall('.//country')
 
for country in countries:
    capital = country.find("capital")
    country.remove(capital)
 
tree.write('countryOutput.xml')