删除带有命名空间的 XML 元素属性

问题描述 投票:0回答:1

我想删除包含命名空间的特定元素的属性。

在以下元素中:

 <CountryCode xsi:nil="true"></CountryCode>
我想删除
xsi:nil="true"
以便在以后的处理中向元素添加值,国家代码(我不能共享整个xml,因为它是为了工作)。

这是我到目前为止尝试过的:

import xml.etree.ElementTree as ET

#path to xml files
xml_path = 'path'
for c in (Path(xml_path).glob('*')):
    file = (str(c))
    if file.endswith(".xml"):
        ns = {'d': 'http://www.w3.org/2001/XMLSchema-instance'}
        tree = ET.parse(file)
        root = tree.getroot()

    #Get specific element
    for e in list(root.findall('ImageSegment', ns)):
        elm = root.find(".//CountryCode")
        **#Remove 'nil' attribute?????**
        elm.attrib.pop('nil', ns)
        ET.dump(elm)

当我用

elm.attrib.pop('nil', ns)
检查元素时,
ET.dump(elm)
行似乎没有任何效果,它返回
<CountryCode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />
。我希望它返回一个空的字典。

我希望xml中的元素是

<CountryCode></CountryCode>

如有任何建议,我将不胜感激。 谢谢

python xml elementtree xml-namespaces xml-attribute
1个回答
0
投票

要删除绑定到命名空间的属性,请使用由大括号分隔的完整命名空间 URI。像这样:

elm.attrib.pop("{http://www.w3.org/2001/XMLSchema-instance}nil")

这也有效:

del elm.attrib["{http://www.w3.org/2001/XMLSchema-instance}nil"]
© www.soinside.com 2019 - 2024. All rights reserved.