2011-01-26 8 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標準ライブラリのPythonに含みます) python 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) 
関連する問題