2016-10-06 62 views
0

夥計們! 我試圖解析一些奇怪的XML:用python和ElementTree分析XML屬性

<?xml version="1.0" encoding="UTF-8"?> 
<analytics> 
    <standard1> 
    ... 
    <attributes> 
     <attribute name="agentname" value="userx userx" /> 
     <attribute name="agentpk" value="5" /> 
     <attribute name="analytics:callid" value="757004000003597" /> 
     ... 
     <attribute name="wrapuptime" value="0" /> 
    </attributes> 
    </standard1> 
    <standard2> 
    ... 
    <attributes> 
     <attribute name="agentname" value="userx userx" /> 
     <attribute name="agentpk" value="5" /> 
     <attribute name="analytics:callid" value="757004000003597" /> 
     ... 
     <attribute name="wrapuptime" value="0" /> 
    </attributes> 
    </standard2> 
    <engines> 
    ... 
    </engines> 
</analytics> 

由於兩個是屬性,我不知道如何通過無需經過整個循環訪問屬性子部分與一個foreach循環。

任何想法如何使用ElementTree直接訪問?

回答

1

您可以使用簡單的XPath表達式來過濾attribute元素的值爲name屬性。示例工作代碼:

import xml.etree.ElementTree as ET 

data = """<?xml version="1.0" encoding="UTF-8"?> 
<analytics> 
    <standard> 
     <attributes> 
     <attribute name="agentname" value="userx userx" /> 
     <attribute name="agentpk" value="5" /> 
     <attribute name="analytics:callid" value="757004000003597" /> 
     <attribute name="wrapuptime" value="0" /> 
     </attributes> 
    </standard> 
</analytics> 
""" 

root = ET.fromstring(data) 
print(root.find(".//attribute[@name='agentname']").attrib["value"]) 

打印:

userx userx 

謹防xml.etree.ElementTreelimited XPath support

+0

@ e-pirate好吧,我還不確定你到底在幹什麼,但你可以調整表達式,例如, '。//標準2 //屬性/屬性[@名稱='代理名稱']'.. ..有幫助。 – alecxe

+0

@ e-pirate請參閱更新的XML。我需要選擇要搜索的特定標準X的哪些屬性子部分。 –

+0

@ e-pirate好的,讓我們以不同的方式處理它。你可以發佈什麼是你想要的輸出在問題XML中呈現嗎?謝謝。 – alecxe