2015-10-04 95 views
1

我有一個XML文件,如下所示。使用ElementTree分析XML與python

<queries> 
<query name="Select" statement="select * from customer_organization"> 
    <filters> 
    <filter id="Select" name="Customer" type="text"></filter> 
    <filter id="Select" name="Start Date" type="date"></filter> 
    <filter id="Select" name="End Date" type="date"></filter> 
    </filters> 
</query> 
<query name="Insert" statement="insert into customer_organization"> 
    <filters> 
    <filter id="Insert" name="From Date" type="date"></filter> 
    <filter id="Insert" name="To Date" type="date"></filter> 
    </filters> 
</query> 
</queries> 

現在我需要用python.I解析它來獲取「查詢」標籤的名字與曾嘗試elementtree.But其上顯示什麼我console.Can請你幫我一下吧,因爲我是python的新手。

import xml.etree.ElementTree 
e = xml.etree.ElementTree.parse('form.xml').getroot() 
for s in e.findall('query'): 
    print(s.get('name')) 
+0

我測試你的代碼,我得到兩行:「選擇」和「插入」。 – idjaw

+0

爲什麼我沒有得到輸出 – newbie

回答

0

所以我剛剛測試了你的代碼。它工作正常。

>>> Select 
>>> Insert 

另一種方法是使用xpath()

import lxml.html 

ttt = """<queries> 
<query name="Select" statement="select * from customer_organization"> 
    <filters> 
    <filter id="Select" name="Customer" type="text"></filter> 
    <filter id="Select" name="Start Date" type="date"></filter> 
    <filter id="Select" name="End Date" type="date"></filter> 
    </filters> 
</query> 
<query name="Insert" statement="insert into customer_organization"> 
    <filters> 
    <filter id="Insert" name="From Date" type="date"></filter> 
    <filter id="Insert" name="To Date" type="date"></filter> 
    </filters> 
</query> 
</queries>""" 


page = lxml.html.fromstring(ttt) 

print page.xpath('.//query/@name')