簡體   English   中英

如何使用ElementTree獲取XML樹中下一個孩子的屬性值

[英]How to get attribute value of next child in XML tree using ElementTree

我正在使用ElementTree解析XML文件。 但是我不知道在解析時如何訪問下一個元素。 我想做的是,如果對應於下一個孩子的相同標簽相同,則將特定標簽打印到文件中。 例如。 如果第五個元素的code標簽是12345,而第六個元素的code標簽也是12345,那么我想將代碼打印在文件中。

就像是:

for child in root:
    if child.find('code').text == next(child).find('code').text:
        file.write(child.find('code').text + "\n")

這已經過測試,應該可以工作:

it = root.iter('code')
prev = it.next()
for current in it:
    if prev.text == current.text:
         print prev.text
    prev = current

您也可以使用zip

for current, next in zip(codes, codes[1:]):
    print map(lambda node: node.find('code').text, [current, next])

暫無
暫無

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

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