我正在尝试根据某些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”并且地址列表“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 :(得分: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