Search code examples
pythonxmlparsingelementtreeminidom

Nested XML parsing using python Element Tree or Minidom


Im struggling to get an xml file parsed using python as it has a nested structure.

My XML file looks like below

<?xml version="1.0" encoding="UTF-8"?>
<DvMCLIResult version="8.6.0-00">
<CommandResult command="GetStorageArray">
<StorageArray objectID="ARRAY.R800.20454" name="POD1_SU73CYBSVSPF01" 
description="VSP G1500 (20454) at 10.181.35.238" serialNumber="20454" 
arrayFamily="R800" arrayType="R800" ...output truncated as I have similar 50 
values...... />
</CommandResult>
</DvMCLIResult>

Im looking to get the information of the "StorageArray" in two variables, like

Key & value. Eg. (Key should get the value "objectID" & value should get "ARRAY.R800.20454" and so on for all the remaining items in a loop. The "StorageArray" has over 50 items in it hence I have truncated the XML file.

I would be printing out the values as below

Key,Value
objectID,ARRAY.R800.20454
name,POD1_SU73CYBSVSPF01
description,VSP G1500 (20454) at 10.181.35.238
serialNumber,20454
arrayFamily,R800
arrayType,R800 and so on

My code:

def  Parse_GetStorageArray():
# Parse the XML to the text file as "Component" "Identifier" "Status"    
#"Result" format
    xmlfile = HiCommandCLI_XML_Path+'/GetStorageArray.xml'
    with open(xmlfile, 'rt') as f:
      tree = ElementTree.parse(f)

      for element in tree.getiterator('StorageArray'):
          items=element.getchildren()
          for content in items:
              print (content.tag)

Solution

  • Your problem is with this line:

        items=element.getchildren()
    

    The StorageArray element does not have any children; it only has attributes.

    You should use this instead:

        items = element.attrib
    

    items will be a dictionary that you can then iterate over...

    {'objectID': 'ARRAY.R800.20454', 
    'name': 'POD1_SU73CYBSVSPF01',
    'description': 'VSP G1500 (20454) at 10.181.35.238', 
    'serialNumber': '20454',
    'arrayFamily': 'R800', 
    'arrayType': 'R800'}