简体   繁体   中英

How to iterate by more than first accepted element in ElementTree

What should I use to iterate more than one element? The code extracts only the first one that is fulfilled, in this case - 'PROCESSING_LEVEL" and then probably ends its function. When I swap these elements, the situation is reversed. I'm trying to make an app to extract and parse the metadata from XML.

tree = ET.parse(filepath)
root: Element = tree.getroot()

for Processing_level in root.iter('PROCESSING_LEVEL' or 'processingLevel'):
    print(f'Processing level: {Processing_level.text}') #console
    text.insert('1.0', Processing_level.text + '\n') #gui
    text2.insert('1.0', Processing_level.text + '\n') #gui`

I tried to use other libraries, but I feel like ET is the proper one. I didn't find other method to make it clear to import.xml attributes from tags in different files. enter image description here

root.iter() function iterates more than one element. If you need only specific elements, you can add an if condition in python to a list.

b.xml :- sample xml file

<root>
  <PROCESSING_LEVEL>LH</PROCESSING_LEVEL>
  <test2>34</test2>
  <processingLevel>2A</processingLevel>
  <test>23</test>
</root>

main.py :

from xml.etree import ElementTree as ET

tree = ET.parse("b.xml")
root: ET.Element = tree.getroot()


for Processing_level in root.iter():
  if(Processing_level.tag in ['PROCESSING_LEVEL','processingLevel']):
    print(f'Processing level: {Processing_level.text}') #console

output :

Processing level: LH
Processing level: 2A

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