【问题标题】:hasAttribute in lxml?lxml中的hasAttribute?
【发布时间】:2013-06-03 12:38:44
【问题描述】:
path4 = file.xpath('/p:sld/p:cSld/p:spTree/p:sp/p:nvSpPr/p:nvPr/p:ph[@type="body"][@sz="quarter"][@marL=True]', namespaces={'p':'http://schemas.openxmlformats.org/presentationml/2006/main',
            'a':'http://schemas.openxmlformats.org/drawingml/2006/main'})

这是我用于解析的 xml 文件的路径。我使用x.hasAttribute('marL') == True: 使用ElementTree 但我不知道如何在lxml 中使用hasAttribute 来检查p:ph 是否包含名为marL 的属性。我尝试了上述方法,但效果很好,而且我在 lxml 示例中也没有找到它。任何人都可以建议hasAttribute 的 lxml 中的功能是什么或在上述实例中使用它吗?

任何帮助将不胜感激!

【问题讨论】:

    标签: xpath python-2.7 attributes lxml


    【解决方案1】:

    属性存在的 xpath 谓词很简单:[@marL] 因此尝试:

    '/p:sld/p:cSld/p:spTree/p:sp/p:nvSpPr/p:nvPr/p:ph[@type="body"][@sz="quarter"][@marL]'
    

    或:

    '/p:sld/p:cSld/p:spTree/p:sp/p:nvSpPr/p:nvPr/p:ph[@type="body" and  @sz="quarter"  and  @marL]'
    

    有关谓词的更多信息,请查看例如 here
    employee[@secretary and @assistant] 选择上下文节点的所有员工子节点,它们同时具有秘书属性和助理属性”

    【讨论】:

    • 这很完美,但是如何检查 p:ph 是否具有属性类型、季度而不是 marl i,例如 x.hasAttribute('marL') == False。我需要使用此条件从标签中获取不同的文本。我试过 @marL=False 哪个有效!
    • 对不起,我不明白检查“是否 p:ph”。 Xaph 例如 :'//p:ph[@type="body" and @sz="quarter" and @marL]' 将返回所有满足“谓词中的过滤条件的 p:ph。
    • 没错,但我想检查p:ph 标记是否具有@type='body'@sz="quarter" 属性,并检查它是否包含名为@marL 的属性。如果是 True 或者如果 p:ph 没有属性 marL 则为 false。我希望它现在更有说服力!
    • 为了更简单,这是使用 ElementTree if all10.nodeName == 'a:pPr' and all10.getAttribute('lvl') == '2' and all10.hasAttribute('marL') == False: 的行,我想用 lxml 重写它!
    • http://stackoverflow.com/questions/16912361/rewrite-elementtree-code-in-lxml 了解更多详情。谢谢!
    【解决方案2】:

    试试

    path4 = file.xpath('boolean(/p:sld/p:cSld/p:spTree/p:sp/p:nvSpPr/p:nvPr/p:ph[@type="body"][@sz="quarter"]/@marL)', namespaces={'p':'http://schemas.openxmlformats.org/presentationml/2006/main',
                'a':'http://schemas.openxmlformats.org/drawingml/2006/main'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 2018-12-07
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 2017-11-30
      相关资源
      最近更新 更多