0

I want to remove an attribute of a specific element, which includes a namespace.

In the following element: <CountryCode xsi:nil="true"></CountryCode> I want to remove xsi:nil="true" in order to add a value to the element, Country Code in later processing (I cannot share the entire xml because its for work).

Here is what I've tried so far:

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)

The line , elm.attrib.pop('nil', ns) does not seem to have any effect when I check the element with ET.dump(elm) , which returns <CountryCode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />.I expect it to return an empty dict.

I would like the element in the xml to be <CountryCode></CountryCode>

I would appreciate any suggestions. Thank you

1 Answer 1

0

To delete an attribute bound to a namespace, use the full namespace URI delimited by curly braces. Like this:

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

This also works:

del elm.attrib["{http://www.w3.org/2001/XMLSchema-instance}nil"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.