2017-09-06 89 views
0

我想解析基於某些XML屬性的XML元素。我的XML文件是:搜索XML屬性來解析XML元素

<?xml version="1.0" encoding="utf-8"?> 
<products updated="9/1/2017"> 
    <product name="o365"> 
    <addresslist type="IPv6"> 
     <address>2603:1020:200::682f:a1d8/128</address> 
     <address>2603:1020:201::3c4/128</address> 
     <address>2603:1030:603::6a/128</address> 
     <address>2603:1030:603::72/128</address> 

我不能讓我的代碼工作,但我懷疑有更好的方法來解決這個問題。我想所有地址元素;如果產品名稱= 「O365」和AddressList中是「TYPE =」 IPv6" 的我的代碼是:

tree = ET.fromstring(r.text) 

for node in tree.iter('product'): 
    list = node.attrib.get('addresslist') 
    address = node.attrib.get('address') 
    if list and address: 
     print ' %s :: %s' % (list, address) 
    else: 
     print name 
+0

您使用的是內置的ElementTree,或者你有還安裝了lxml嗎? – Tomalak

回答

0

這個工作對我來說:

import xml.etree.ElementTree as ET 

tree = ET.parse('1.xml') 

for x in tree.iter('product'): 
if x.attrib.get('name') == 'o365': 
    for y in tree.iter('addresslist'): 
     if y.attrib.get('type') == 'IPv6': 
      for z in tree.iter('address'): 
       print z.text 

與下面的輸出:

2603:1020:200::682f:a1d8/128 
2603:1020:201::3c4/128 
2603:1030:603::6a/128 
2603:1030:603::72/128 
+0

所以這裏是我解析的完整URL:https://support.content.office.net/en-us/static/O365IPAddresses.xml。當我運行你的代碼時,它顯示的條目多於IPv6部分? (我不期望它) – EthanB