使用命名空间查找XPATH并基于父元素

时间:2012-02-19 21:51:26

标签: python xml xpath lxml

我有以下xml:

...
    <chapter>
        <start_time>00:01:04</start_time>
    </chapter>  
    <chapter>
        <start_time>00:01:05</start_time>
    </chapter>  
...

目前,为了获得我正在做的start_times:

start_times = node.xpath("//t:start_time/text()", 
                   namespaces={'t':'http://example.com/namespace'})

但是,我也从非章节元素中获取start_times

[00:00:01, 00:00:02, 00:01:04, 00:01:05]

此外,由于某些原因,起诉//t:chapter/start_time会返回空结果。

我如何只获得父元素为start_times的{​​{1}}?

1 个答案:

答案 0 :(得分:1)

使您的选择器更加具体:

start_times = node.xpath("//t:chapter/start_time/text()", 
                   namespaces={'t':'http://example.com/namespace'})