2011-01-26 21 views
8

'de birden çok öznitelik kullanılarak olay bulun. Aşağıdaki XML'e sahibim.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> 

S: Nasıl düğüm <testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" /> bulabilirim? tree.find() işlevini buluyorum, ancak bu işlevin parametresi öğe adı gibi görünüyor.

Düğüm temelini temel alarak bulmam gerekiyor: name = "VHDL_BUILD_Passthrough" AND classname="TestOne".

+0

'Testsuite' etiketiniz kapalı değil mi? – eumiro

+0

@eumiro: bir yazım hatasıydı, bunu işaretlediğiniz için teşekkürler. – prosseek

cevap

17

Bu kullanmakta olduğunuz sürüm bağlıdır. dahil, maalesef

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

Eğer elementtree (1.2 önceki bir sürümünü kullanıyorsanız: Eğer elementtree 1.3+ varsa [@attrib=’value’] gibi described in the docs olarak, temel bir xpath ifade kullanabilirsiniz (2,7 standart kütüphanesinde Python dahil) python 2.5 ve 2.6 için standart kütüphanede bu kolaylığı kullanamazsınız ve kendinizi filtrelemeniz gerekir.

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 Günü kurtardınız ... teşekkürler :) – ATOzTOA

0

Sen şöyle, var <testcase /> öğeleri boyunca yineleme gerekecek:

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)