Home > front end >  How can I access the value from this complex and strange XML? (subsubsubclass)
How can I access the value from this complex and strange XML? (subsubsubclass)

Time:01-21

I'm new to working with XML files. I don't know how can I read the properties only from the object 'Convergence' and how can I access the value of 'Molar Flow'.

<?xml version="1.0" encoding="utf-8"?>
<Objects>
  <Object name="Convergence" type="Material Stream">
    <Property name="Temperature" value="20" units="C" />
    <Property name="Pressure" value="2" units="bar" />
    <Property name="Mass Flow" value="36" units="kg/h" />
    <Property name="Molar Flow" value="19" units="mol/h" />
  <Object name="P-1, HE-1" type="Material Stream">
    <Property name="Temperature" value="25" units="C" />
    <Property name="Pressure" value="1" units="bar" />
    <Property name="Mass Flow" value="2" units="kg/h" />
    <Property name="Molar Flow" value="103" units="mol/h" />
    <Property name="Volumetric Flow" value="0.9" units="m3/h" />
  </Object>
</Objects>

I tried this code to print out all Properties of "Convergence", but it gave me just an empty output. Thanks a lot!

import xml.etree.ElementTree as ET

tree = ET.parse("simulation.xml")
root = tree.getroot()
for neighbor in root.iter('Property'):
    if neighbor in root.findall("./[@object = 'Convergence']"):
        print(neighbor.attrib)`

CodePudding user response:

The xpath in your .findall() doesn't make much sense.

Maybe instead of doing a .iter() and then a .findall(), you just do the findall with a predicate on Object...

import xml.etree.ElementTree as ET

tree = ET.parse("simulation.xml")
for prop in tree.findall(".//Object[@name='Convergence']/Property"):
    print(prop.attrib)

This will print the attributes (.attrib is a dictionary with each attribute name/value) of the Property elements that are children of Object when Object has an attribute name with the value of Convergence.

Example printed output:

{'name': 'Temperature', 'value': '20', 'units': 'C'}
{'name': 'Pressure', 'value': '2', 'units': 'bar'}
{'name': 'Mass Flow', 'value': '36', 'units': 'kg/h'}
{'name': 'Molar Flow', 'value': '19', 'units': 'mol/h'}
  • Related