简体   繁体   中英

How to get element's data in following xml code using ElementTree in python?

<?xml version="1.0" encoding="us-ascii"?>
<Network id="5-Bus Test System" BaseKVAvalue="l00" unit="mva">
<BusList defaultBaseV="13800" unit="volt"> 
<Bus id="l" type="pq"> 
<P value="l.6" unit="pu"/> 
<Q value="0.8" unit="pu"/> </Bus> 
</BusList> 
</Network>

what command should we use to get the bus's element data ie P ,Q values to print as output

I tried this 2 statements to extract the data

print(root[0][0]).text  and print(root[0][0]).tail

but it is giving none as output for both

for the below statement output is giving only its attribute but not data

print(root[0][0]).attrib

ouptut is {'type': 'pq', 'id': 'l'}

I prefer looking up nodes by name. The following is one way to retrieve the attributes of the P and Q elements:

from xml.etree import ElementTree as ET

tree = ET.parse("network.xml")

print tree.find("BusList/Bus/P").attrib
print tree.find("BusList/Bus/Q").attrib

Output:

{'unit': 'pu', 'value': 'l.6'}
{'unit': 'pu', 'value': '0.8'}

But if you want to access the nodes by index, you can do it like so:

root = tree.getroot()
print root[0][0][0].attrib
print root[0][0][1].attrib

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