10

私は次のXMLを持っています。

<?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"

4

2 に答える 2

24

これは、使用しているバージョンによって異なります。ElementTree 1.3+ (Python 2.7 標準ライブラリを含む) を使用している場合は、ドキュメントで説明されているように、次のような基本的な xpath 式を使用できます[@attrib='value']

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

残念ながら、以前のバージョンの ElementTree (1.2、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']
于 2011-01-26T19:57:15.517 に答える
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)
于 2011-01-26T19:50:15.437 に答える