[英]Printing a selected portion from multiple tags of same name of XML files using python
您好,我的XML文件是這樣的,有人可以幫我從XML文件中獲取特定的標簽:
<A1> <A><B>TEST1</B></A> <A><B>TEST2</B></A> <A><B>TEST3</B></A> </A1> <A1> <A><B>TEST4</B></A> <A><B>TEST5</B></A> <A><B>TEST6</B></A> </A1>
到現在為止,我正在python中像這樣處理它:
for A in A1.findall('A'):
B = A.find('B').text
print B
print B is giving me output like this:
Test1
Test2
Test3
Test4
Test5
Test6
I want output from only first tag like this:
Test1
Test4
What changes should I do to make it work?
好吧,讓我們再試一次。 因此,在修訂后,我們要搜索文檔,並且每次出現父標記(A1)時,我們都希望獲取每個集合中第一個標記的內容。
讓我們嘗試一個遞歸函數:
xmlData = open('xml.txt').readlines()
xml = ''.join(xmlData)
def grab(xml):
""" Recursively walks through the whole XML data until <A1> is not found"""
# base case, if the parent tag (<A1>) isn't there, then return
if xml.find('<A1>') == -1:
return
else:
# find the location of the parent tag
open_parent = xml.find('<A1>')
close_parent = open_parent + 4
# find the first child tag
open_child = xml.find('<a><b>', close_parent)
close_child = xml.find('</b></a>', open_child)
# grab the data within that tag
child_data = xml[open_child + 6 : close_child]
print(child_data)
# recursively call the grab() function
return grab(xml[close_child:])
出於興趣,您是否已經有解決方案,也不想共享?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.