簡體   English   中英

使用elementTree,python解析xml文檔

[英]parsing xml document using elementTree, python

import xml.etree.ElementTree as ET

tree = ET.parse("Parsed.xml")
doc = tree.getroot()

for elem in doc.findall('.//medicationsInfo/entryInfo/productCode/code'):
    print (elem.text);

for elem in doc.findall('.//medicationsInfo/entryInfo/productCode/codeSystem'):
    print (elem.text);  

在上面的python代碼中,我通過指定路徑獲取代碼和codeSystem的值,但它們首先打印所有代碼然后打印所有codeSystem。 我想並行打印它們(如列方式),那么如何編輯上面的代碼來解析我的xml doc。

例如,我看到我有這種方式的xml,我想按列打印代碼和codeSystem。

這不是最好的方法,但應該有效。 我們掃描xml尋找codecodeSystem ,相信它們總是成對出現(應該由xml架構強制執行)。

我們創建兩個列表,其中一個code vaules,另一個為codeSystem ,然后通過遍歷它們來重新創建對,從而輸出列表。

codeList=[]
codeSystemList=[]

for elem1 in doc.findall('.//medicationsInfo/entryInfo/productCode/code'):
    codeList.append(elem1.text)

for elem2 in doc.findall('.//medicationsInfo/entryInfo/productCode/codeSystem'):
    codeSystemList.append(elem2.text)


for i in range(len(codeList)):
    print(codeList[i],codeSystemList[i])

注意:在問題中提供新信息后,此答案已更新,因此應忽略前幾條評論

暫無
暫無

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

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