如何使用 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>

我们应该使用什么命令来获取总线的元素数据,即要打印为输出的 P、Q 值

我尝试了这 2 个语句来提取数据

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

但它给出 none 作为两者的输出

因为下面的语句输出只给出了它的属性而不是数据

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

输出为 {'type': 'pq', 'id': 'l'}

我更喜欢按名称查找节点。以下是检索 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

输出:

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

但是如果你想通过索引访问节点,你可以这样做:

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