【问题标题】:Python 2 XML Etree xpath : Getting Predicate error while try to parse variable in attribute check, like [@attrib ='VAL'] but using [@attrib = '%s']Python 2 XML Etree xpath:尝试在属性检查中解析变量时出现谓词错误,如 [@attrib ='VAL'] 但使用 [@attrib = '%s']
【发布时间】:2020-05-08 13:20:01
【问题描述】:

示例 XML:

<ParentTag TEST_ID="xxxxxx" ID="1">
    <Child TagType="Manual">
        <Manhrs Cost="100"/>
        <Testing VAL="RANDOM STRING"/>
    </Child>
    <Child TagType="Automated">
        <Manhrs Cost="10"/>
        <Testing VAL="RANDOM STRING2"/>
    </Child>
</ParentTag>
<ParentTag TEST_ID="YYYYYY" ID="1">
    <Child TagType="Manual">
        <Manhrs Cost="100"/>
        <Testing VAL="RANDOM STRING"/>
    </Child>
    <Child TagType="Automated">
        <Manhrs Cost="10"/>
        <Testing VAL="RANDOM STRING2"/>
    </Child>
</ParentTag>
<ParentTag TEST_ID="ZZZZZZZ" ID="1">
    <Child TagType="Manual">
        <Manhrs Cost="100"/>
        <Testing VAL="RANDOM STRING"/>
    </Child>
    <Child TagType="Automated">
        <Manhrs Cost="10"/>
        <Testing VAL="RANDOM STRING2"/>
    </Child>
</ParentTag>

所以如果我运行:

TEST_ID = xxxxxx
for n in root.findall("ParentTag[@TEST_ID = '%s']//Child[@TagType = 'Automated']", % TEST_ID):
        print("FOUND")

错误:python2.7/xml/etree/ElementPath.py",第 224 行,在 prepare_predicate 中 引发 SyntaxError("无效谓词") SyntaxError: 无效谓词

请注意,上面相同的代码在 python 3 中确实可以工作,但我需要它在 Python 2.7 中工作 如果除了在 python 2 中循环多次之外还有其他选择,请提供相同的方法

我还必须使用 xml.etree.ElementTree

【问题讨论】:

    标签: python-2.7 xml.etree


    【解决方案1】:

    由于属性和值之间有空格而不是空格,所以应该像这样定义它:[@TEST_ID='{}']".format(value)

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 2013-05-31
      • 2022-01-04
      相关资源
      最近更新 更多