Edited to reword question.
The problem in the attached code is that as soon as we enter the for loop the variables: gcOne, gcTwo, gcThree are out of scope, so I cannot use them inside the for loop (in the print statement 2 there is nothing to print).
How to pass or use the local variables gcOne, gcTwo, gcThree in the for loop?
Thanks.
#!/usr/local/bin/python3.10
# Ensure this script will run using Python 3.10
# Include some libraries
import xml.etree.ElementTree
xml_tree = xml.etree.ElementTree.parse("sampledata.xml")
root = xml_tree.getroot()
gcOne="1"
gcTwo="2"
gcThree="3"
# Read the XML file
def process_xml(element, gcOne, gcTwo, gcThree):
element_tag = element.tag
element_attributes = element.attrib if len(element.attrib) else ""
element_text = element.text if element.text is not None and len(element.text.strip()) > 0 else ""
element_tail = element.tail.strip() if element.tail is not None and len(element.tail.strip()) > 0 else ""
if element_tag == "gcA":
gcOne=element_text
if element_tag == "gcB":
gcTwo=element_text
if element_tag == "gcC":
gcThree=element_text
# Now do something with gcOne, gcTwo and gcThree because we have values for all 3 variables (note: assumes this order in the xml file for simplicity)
# This line is printing the value of one of gcOne or gcTwo or gcThree
print ("1 ", gcOne, gcTwo, gcThree)
# Read further elements recursively
element_children = list(element)
for child in element_children:
# This is not printing any of gcOne, gcTwo, gcThree but always prints 1, 2, 3
print ("2 ", gcOne, gcTwo, gcThree)
process_xml(child, gcOne, gcTwo, gcThree)
return gcOne, gcTwo, gcThree
# Main
process_xml(root, gcOne, gcTwo, gcThree)