Home > Net >  retrieving xml element value by searching the element by substring in its name
retrieving xml element value by searching the element by substring in its name

Time:01-11

I would need to retrieve xml element value by searching the element by substring in its name, eg. I would need to get value for all elements in XML file which names contains client.

I found a way how to find element with xpath by an attribute, but I haven't find a way for element name.

CodePudding user response:

If you're really using lxml (you have the question tagged both lxml and elementtree), you can use the xpath function contains() in a predicate...

from lxml import etree

xml = """
<doc>
    <client1>foo</client1>
    <some_client>bar</some_client>
</doc>
"""

root = etree.fromstring(xml)

for elem in root.xpath("//*[contains(name(),'client')]"):
    print(f"{elem.tag}: {elem.text}")

printed output...

client1: foo
some_client: bar

ElementTree only has limited xpath support, so one option is to check the name of the element using the .tag property...

import xml.etree.ElementTree as etree

xml = """
<doc>
    <client1>foo</client1>
    <some_client>bar</some_client>
</doc>
"""

root = etree.fromstring(xml)

for elem in root.iter():
    if "client" in elem.tag:
        print(f"{elem.tag}: {elem.text}")

This produces the same printed output above.

  • Related