0

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.

JanFi86
  • 449
  • 10
  • 29

1 Answers1

2

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.

Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • thanks @Daniel Haley, is there a way how to do that in ElementTree as well? – JanFi86 Jan 10 '23 at 22:40
  • @JanFi86 - Not through xpath. ElementTree only provides [limited support](https://docs.python.org/3/library/xml.etree.elementtree.html#xpath-support). You'd have to check every elements name (the `.tag` property like shown in my print() example). Let me know if you'd like me to update my answer with an example. – Daniel Haley Jan 10 '23 at 22:42
  • I would appreciate If you would add ElementTree example as well, thanks – JanFi86 Jan 10 '23 at 22:46
  • 1
    @JanFi86 - Answer updated. Hopefully that helps. – Daniel Haley Jan 10 '23 at 22:46