2013-05-31 105 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