python xml:带有具有特定属性值的childer的元素的xpath

时间:2015-11-11 21:37:46

标签: python xml xpath robotframework

我需要以下的xpath表达式:

所有带有标记" test"的节点有孩子的标签" status"具有名为" status"的属性价值" PASS"

所以使用下面的xml,我需要获得id为#34; s1-t1"的节点。我应该能够修改它,以便使用属性[@status='FAIL']进行测试,而不是通过测试。我尝试了几件事无济于事:

  • ".//test/[@status='PASS']"不返回任何内容
  • ".//test/[status][@status='PASS']"不返回任何内容
  • ".//test//[status][@status='PASS']"抛出一个SyntaxError("无效的后代")
  • ".//test//status[@status='PASS']"返回2个状态节点(一个用于测试状态,一个用于关键字状态)
  • ".//test//status[@status='PASS']/../.."返回正确的测试节点,但也返回套件节点

我不确定此时要尝试什么。这是我正在处理的XML:

<?xml version="1.0" encoding="UTF-8"?>
<robot generated="20151111 16:29:28.630" generator="Robot 2.9.1 (Python 2.7.10 on cygwin)">
<suite source="/cygdrive/c/test/robot/thing.robot" id="s1" name="Thing">
<test id="s1-t1" name="Case1">
<kw name="Should Contain" library="BuiltIn">
<doc>Fails if ``item1`` does not contain ``item2`` one or more times.</doc>
<arguments>
<arg>hello</arg>
<arg>hell</arg>
</arguments>
<status status="PASS" endtime="20151111 16:29:28.689" starttime="20151111 16:29:28.689"></status>
</kw>
<status status="PASS" endtime="20151111 16:29:28.689" critical="yes" starttime="20151111 16:29:28.688"></status>
</test>
<test id="s1-t2" name="Case2">
<kw name="Should Contain" library="BuiltIn">
<doc>Fails if ``item1`` does not contain ``item2`` one or more times.</doc>
<arguments>
<arg>hello</arg>
<arg>elo</arg>
</arguments>
<msg timestamp="20151111 16:29:28.690" level="FAIL">'hello' does not contain 'elo'</msg>
<status status="FAIL" endtime="20151111 16:29:28.690" starttime="20151111 16:29:28.690"></status>
</kw>
<status status="FAIL" endtime="20151111 16:29:28.690" critical="yes" starttime="20151111 16:29:28.690">'hello' does not contain 'elo'</status>
</test>
<test id="s1-t3" name="Case3">
<kw name="Should Contain" library="BuiltIn">
<doc>Fails if ``item1`` does not contain ``item2`` one or more times.</doc>
<arguments>
<arg>hello</arg>
</arguments>
<msg timestamp="20151111 16:29:28.691" level="FAIL">Keyword 'BuiltIn.Should Contain' expected 2 to 4 arguments, got 1.</msg>
<status status="FAIL" endtime="20151111 16:29:28.691" starttime="20151111 16:29:28.691"></status>
</kw>
<status status="FAIL" endtime="20151111 16:29:28.691" critical="yes" starttime="20151111 16:29:28.691">Keyword 'BuiltIn.Should Contain' expected 2 to 4 arguments, got 1.</status>
</test>
<status status="FAIL" endtime="20151111 16:29:28.692" starttime="20151111 16:29:28.633"></status>
</suite>
<statistics>
<total>
<stat fail="2" pass="1">Critical Tests</stat>
<stat fail="2" pass="1">All Tests</stat>
</total>
<tag>
</tag>
<suite>
<stat fail="2" id="s1" name="Thing" pass="1">Thing</stat>
</suite>
</statistics>
<errors>
</errors>
</robot>

1 个答案:

答案 0 :(得分:1)

你快到了:

.//test[status/@status = "PASS"]

这正是所有标记为“test”的节点,其子标签为“status”且具有名为“status”的属性,其值为“PASS”