2011-01-26 2 views
8

다음 XML을 가지고 있습니다.ElementTree/Python에서 여러 속성을 사용하여 일치를 찾으십시오.

<?xml version="1.0" encoding="UTF-8"?> 
<testsuites tests="10" failures="0" disabled="0" errors="0" time="0.001" name="AllTests"> 
    <testsuite name="TestOne" tests="5" failures="0" disabled="0" errors="0" time="0.001"> 
    <testcase name="DefaultConstructor" status="run" time="0" classname="TestOne" /> 
    <testcase name="DefaultDestructor" status="run" time="0" classname="TestOne" /> 
    <testcase name="VHDL_EMIT_Passthrough" status="run" time="0" classname="TestOne" /> 
    <testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" /> 
    <testcase name="VHDL_SIMULATE_Passthrough" status="run" time="0.001" classname="TestOne" /> 
</testsuite> 
</testsuites> 

Q : 어떻게 노드 <testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" />를 찾을 수 있습니까? tree.find() 함수를 찾았지만이 함수의 매개 변수는 요소 이름처럼 보입니다.

속성 : name = "VHDL_BUILD_Passthrough" AND classname="TestOne"을 기반으로 노드를 찾아야합니다.

+0

'testsuite' 태그가 닫혀 있지 않습니까? – eumiro

+0

@eumiro : 오타였습니다. 지적 해 주셔서 감사합니다. – prosseek

답변

17

이것은 당신이 사용중인 버전에 따라 다릅니다. 포함, 불행하게도

x = ElmentTree(file='testdata.xml') 
cases = x.findall(".//testcase[@name='VHDL_BUILD_Passthrough'][@classname='TestOne']" 

당신이 ElementTree (1.2 이전 버전을 사용하는 경우 : 당신이 ElementTree 1.3 이상이있는 경우 [@attrib=’value’]처럼 described in the docs로, 기본 XPath 식을 사용할 수 있습니다 (2.7 표준 라이브러리 파이썬에 포함) 파이썬 2.5 및 2.6 용 표준 라이브러리에서) 당신은 그 편리함을 사용할 수없고 자신을 필터링해야합니다.

x = ElmentTree(file='testdata.xml') 
allcases = x12.findall(".//testcase") 
cases = [c for c in allcases if c.get('classname') == 'TestOne' and c.get('name') == 'VHDL_BUILD_Passthrough'] 
+0

+1 당신이 하루를 저장 ... 감사합니다 :) – ATOzTOA

0

당신은 당신이 이렇게 같이있는 <testcase /> 요소를 반복해야합니다 :

from xml.etree import cElementTree as ET 

# assume xmlstr contains the xml string as above 
# (after being fixed and validated) 
testsuites = ET.fromstring(xmlstr) 
testsuite = testsuites.find('testsuite') 
for testcase in testsuite.findall('testcase'): 
    if testcase.get('name') == 'VHDL_BUILD_Passthrough': 
     # do what you will with `testcase`, now it is the element 
     # with the sought-after attribute 
     print repr(testcase) 
관련 문제