简体   繁体   English

如何在python中使用ElementTree在以下xml代码中获取元素的数据?

[英]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 我们应该使用什么命令来获取总线的元素数据,即P,Q值以打印为输出

I tried this 2 statements to extract the data 我尝试了这2条语句来提取数据

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'} ouptut是{'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: 以下是检索PQ元素的属性的一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM