简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM