Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

retrieving xml element value by searching the element by substring in its name

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading