2013-05-31 118 views
0

我正在構建一個簡單的解析器來處理工作中的常規數據饋送。這篇文章XML to csv(-like) format非常有幫助。我在解決方案中使用for循環來循環遍歷所需的所有元素/子元素,但仍然有點卡住。使用Python解析XML時定位特定的子元素

例如,我的XML文件的結構如下所示:

<root> 
    <product> 
    <identifier>12</identifier> 
    <identifier>ab</identifier> 
    <contributor>Alex</contributor> 
    <contributor>Steve</contributor> 
    </product> 
<root> 

我想要的目標只有第二標識,只有第一功臣。關於我該怎麼做的任何建議?

乾杯!

回答

0

您指出的另一個答案有一個如何將標記的所有實例轉換爲列表的示例。 。你可以只通過這些循環,並丟棄你不感興趣的那些

然而,有一種方法可以直接使用XPath做到這一點:迷你語言支持項指標中括號:

import xml.etree.ElementTree as etree 
document = etree.parse(open("your.xml")) 

secondIdentifier = document.find(".//product/identifier[2]") 
firstContributor = document.find(".//product/contributor[1]") 
print secondIdentifier, firstContributor 

打印

'ab', 'Alex' 

注意,在XPath中,第一個指標是1,不0

ElementTree的findfindall僅支持XPath的一個子集,描述爲here。關於W3Schools以及W3C's normative document中完整描述的完整XPath可從lxml(第三方軟件包)獲得,但可以廣泛使用。使用lxml,示例如下所示:

import lxml.etree as etree 
document = etree.parse(open("your.xml")) 

secondIdentifier = document.xpath(".//product/identifier[2]")[0] 
firstContributor = document.xpath(".//product/contributor[1]")[0] 
print secondIdentifier, firstContributor 
+0

太好了,謝謝吉姆。我認爲你的例子正是我需要的。首先,大多數產品的每個元素都有不同的數量,所以我最終列出了不同長度的列表,這使得系統地定位我需要的元素更加困難。 – zhogan85