简体   繁体   中英

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

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)`

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'}

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