簡體   English   中英

解析具有多個同名子級的 xml 子級,python

[英]parse xml children with multiple children with same name, python

我有 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>

我想解析 source-IP 中的所有孩子。 輸出應為兩個 IP,而不僅僅是一個。 我想擁有 :

2.104.54.11
172.16.33.11

當多個孩子共享一個 name 時,它類似於Parse XML with Python ,但我懇請您提供所有代碼。

先感謝您。

我試過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)
}

.findall()返回一個項目列表。 您需要遍歷這些項目中的每一個以獲取文本:

for address_ip in tree.find('sub2').find('source-IP').findall('address-IP'):
    print address_ip.text

暫無
暫無

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

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