【问题标题】:How to handle multiple search condition of xpath in python Element Tree如何处理python元素树中xpath的多个搜索条件
【发布时间】:2013-08-07 08:09:03
【问题描述】:

我想使用 Python(2.7.5) ElementTree 通过多个搜索条件从 xml 文件中提取一些元素。 xml 看起来像:

   <src name="BdsBoot.c">
        <fn name="XXXXX" fn_cov="0" fn_total="1" cd_cov="0" cd_total="4">
           <probe line="113" kind="condition" event="full"/>
           <probe line="122" column="10" kind="condition" event="none" />
           <probe line="124" column="9" kind="condition" event="full" />
        </fn>
   </src>

我想要 kind="condition" 和 event="full" 的探测元素

我试过了

root.findall(".//probe[@kind='condition' and @event='full']") —— error
root.findall(".//probe[@kind='condition'] and .//probe[@event='full']") —— nothing

看了here的简单介绍,现在elementtree好像不支持and运算符了?

有没有办法实现这个目标?

【问题讨论】:

    标签: python xpath elementtree


    【解决方案1】:

    使用这个:

    root.findall('.//probe[@kind="condition"][@event="full"]')
    

    演示:

    >>> s
    '<src name="BdsBoot.c">\n        <fn name="XXXXX" fn_cov="0" fn_total="1" cd_cov="0" cd_total="4">\n           <probe line="113" kind="condition" event="full"/>\n           <probe line="122" column="10" kind="condition" event="none" />\n           <probe line="124" column="9" kind="condition" event="full" />\n        </fn>\n   </src>'
    >>> root = ET.fromstring(s)
    >>> root.findall('.//probe[@kind="condition"]')
    [<Element 'probe' at 0x7f8a5146ce10>, <Element 'probe' at 0x7f8a5146ce50>, <Element 'probe' at 0x7f8a5146ce90>]
    >>> root.findall('.//probe[@kind="condition"][@event="full"]')
    [<Element 'probe' at 0x7f8a5146ce10>, <Element 'probe' at 0x7f8a5146ce90>]
    

    【讨论】:

    • 我有一个新问题,如何使用'..'访问父节点?
    • 你最好发布一个新问题。 :(因为你的一句话评论信息很少。我不知道怎么回答。
    • 同上,如果我得到一个'probe'节点,我如何访问它的父节点('fn')?
    • ".//probe[@kind='condition' and @event='full']/.."?我不确定。还是会有find_parent
    • 你是对的!没有从子到父的引用,我必须从根开始找到父。
    猜你喜欢
    • 2013-05-04
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多