Read XML value from a XML string

import xml.etree.ElementTree as ET

    tree = ET.ElementTree(ET.fromstring(my_string))          #Load the XML as an element tree object
    root = tree.getroot()                   #Get root element 
  
    #Look for an item in the XML root called <Result>
    for item in root.findall('Result'): 
        print(item.text)
        if item.text == "Success":
            print("Found success result")

Read XML value from an XML file

import xml.etree.ElementTree as ET

    tree = ET.parse('my_xml_fiil.xml')          #Load the XML as an element tree object
    root = tree.getroot()                   #Get root element 
  
    #Look for an item in the XML root called <Result>
    for item in root.findall('Result'): 
        print(item.text)
        if item.text == "Success":
            print("Found success result")

Parse XML values from an XML file

import xml.etree.ElementTree as ET

    # create element tree object 
    tree = ET.parse('my_xml_file.xml')          #Load the XML as an element tree object
    root = tree.getroot()                       #Get root element 
  
    #Create empty list
    my_items_list = [] 
  
    #Iterate through the XML items 
    for item in root.findall('./something/item'): 
  
        
        my_dictionary = {}          #Create empty dictionary 
  
        #Iterate through the child elements of this XML item 
        for child in item: 
            if child .text != None:
                print("Found item: " + child .tag + "-" + child .text)
                my_dictionary[child.tag] = str(child.text)    #<<Use str() if you want to stop Python turning numeric values into bytes etc
  
        my_items_list.append(my_dictionary) 
      
    return my_items_list
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *