[Solved] Using Python from a XML file ,I want to get only the tags that have a value? [closed]


Load xml, traverse it (eg recursively), return tags with non-empty text.

Here as generator:

import xml.etree.ElementTree as ET

def getNonemptyTagsGenerator(xml):
    for elem in xml:
        yield from getNonemptyTagsGenerator(elem)
    if len(xml) == 0:
        if xml.text and xml.text.strip():
            yield xml

xml = ET.parse(file_path).getroot()
print([elem for elem in getNonemptyTagsGenerator(xml)])

Result:

[<Element 'field' at 0x7fb2c967fea8>, <Element 'text' at 0x7fb2c9679048>]

You said wanted “tags”, so those are the Element objects.

2

solved Using Python from a XML file ,I want to get only the tags that have a value? [closed]