我有xml:
<tree-root>
<sub1>it is sub1</sub1>
<sub2>
<sub3>sub3</sub3>
<position>5584</position>
<source-IP>
<address-IP>2.104.54.11</address-IP>
<address-IP>172.16.33.11</address-IP>
</source-IP>
</sub2>
我想解析源IP内的所有子级。输出应该是两个IP,而不仅仅是一个。 我想要:
2.104.54.11
172.16.33.11
它与Parse XML with Python when multiple children share a name类似,但请提供所有代码。
谢谢。
我尝试了print(tree.find('sub2').find('source-IP').findall('address-IP').text);
,但只出现了错误:
'list' object has no attribute 'text'
这是完整的代码:
print(tree.find('sub2').find('source-IP').find('address-IP').text)
{ import xml.etree.ElementTree as ET
tree = ET.parse('IPs.xml')
root = tree.getroot()
print(root.text)
print(tree.find('sub1').text)
print(tree.find('sub2').find('sub3').text)
print(tree.find('sub2').find('position').text)
print('I would like to print all the IPs below, not just the first one')
print(tree.find('sub2').find('source-IP').find('address-IP').text)
print(tree.find('sub2').find('source-IP').find('address-IP').text)
}
答案 0 :(得分:1)
.findall()
返回项目列表。您需要遍历所有这些项目以获取文本:
for address_ip in tree.find('sub2').find('source-IP').findall('address-IP'):
print address_ip.text