2016-09-21 78 views
0

我正在嘗試使用ElementTree模塊解析Python中的XML文檔。我正在尋找Elements,該標籤中的xml標籤爲entryname屬性爲ipAddress。下面是我到目前爲止的代碼:搜索名稱屬性的XML標籤:Python elementTree模塊

tree = ET.parse(fi2) 
root = tree.getroot() 
for child in root.iter('entry'): #looks through child elements for tag=entry 
    #look for elements that have an attribute(name)='string' 

作爲參考,當我使用for循環內的代碼print child.tag, child.attrib,我得到下面的輸出:

entry {'name': 'ipAddress'} 

我需要幫助尋找entry標籤用的ipAddress

回答

0
import xml.etree.ElementTree as ET 

tree = ET.parse(your_xml) 
root = tree.getroot() 
for child in root: 
    if child.tag=='entry': 
     for node in child: 
      if node.attrib["name"]=='certain_ip': 
       print("found") 
0
tree = ET.parse(fi2) 
root = tree.getroot() 
for child in root.iter('entry'): #looks through child elements for tag=entry 
    #look for elements that have an attribute(name)='string' 
    if ipAddress in child.get('name'): 
     #condition is met. Execute some code. Do your thang 
name attribute