News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

python xml - search for attribute with regular expressions

posted on 2024-12-02 22:10     read(776)     comment(0)     like(29)     collect(2)


In my xml file, I have nodes like this:

<waitingJobs idList="J03ac2db8 J03ac2fb0"/>

I know how to use .findall to search for attributes but now, it looks like I would need to use regular expressions because I can't just use

root.findall('./[@attrib='value']')

I'd have to use

root.findall('./[@attrib='*value*']')

QUESTION

  1. Is this possible with xml.etree?
  2. How do you do this with lxml?

solution


Unfortunately, things like contains() and starts-with() are not supported by xml.etree.ElementTree built-in library. You can manually check the attribute, finding all waitingJobs and using .attrib to get to the idList value:

import xml.etree.ElementTree as ET

data = """<jobs>
    <waitingJobs idList="J03ac2db8 J03ac2fb0"/>
</jobs>
"""

root = ET.fromstring(data)
value = 'J03ac2db8'
print([elm for elm in root.findall(".//waitingJobs[@idList]") 
       if value in elm.attrib["idList"]])

With lxml.etree, you can use xpath() method and contains() function:

import lxml.etree as ET

data = """<jobs>
    <waitingJobs idList="J03ac2db8 J03ac2fb0"/>
</jobs>
"""

root = ET.fromstring(data)

value = 'J03ac2db8'
print(root.xpath(".//waitingJobs[contains(@idList, '%s')]" % value))


Category of website: technical article > Q&A

Author:qs

link:http://www.pythonblackhole.com/blog/article/247242/8778639f30284bc02dec/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

29 0
collect article
collected

Comment content: (supports up to 255 characters)