簡體   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>

我們應該使用什么命令來獲取總線的元素數據,即P,Q值以打印為輸出

我嘗試了這2條語句來提取數據

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

但是它都沒有給出任何輸出

對於以下語句,輸出僅給出其屬性,而不給出數據

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

ouptut是{'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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM