用Python逐块读取XML
我刚开始学习Python,手上有一个XML文件。我想要逐个读取里面的每个测试数据块(testdata),并查看这些数据块中的子元素。简单来说,我想先读取这个文件,然后一个一个地处理每个测试数据块。比如说,如果某个数据块的行号是1,并且它的执行标记是“no”,那么就跳过这个数据块。接下来,我会读取这个测试数据块中的子元素,获取其中的行值。然后再获取“search”和“found”的值。等这些都读取完后,我会写自己的代码来处理这些数据。完成这段代码后,我会回到行号为2的测试数据块,按照和行号1一样的方式读取数据,然后运行我写的代码,依此类推,直到所有的测试数据块都处理完。我现在使用的是Python2.7,非常希望能得到帮助,因为我卡住了!
<?xml version="1.0" ?>
<data>
<testdata row="1" execute="yes" regression = "no">
<command>Text command1</command>
<command> Text command2</command>
<command> Text command3</command>
<command> Text command4</command>
<command> Text command5</command>
<command> Text command6</command>
<command> Text command7</command>
<command> Text command8</command>
<verification> search ="verify" found ="yes" </verification>
</testdata>
<testdata row="2" execute="yes" regression = "no">
<command>Display Command 1</command>
<command>Display Command 2</command>
<command>Display Command 3</command>
<command>Display Command 4</command>
<command>Display Command 5</command>
<command>Display Command 6</command>
<command>Display Command 7</command>
<command>Display Command 8</command>
<verification> search ="find" found ="yes" </verification>
</testdata>
</data>
2 个回答
-1
如果你使用etree库来解析这些数据,你可以得到如下结果:
import xml.etree.ElementTree as ET
parsed_element = ET.fromstring(xml)
for child in parsed_element.findall('testdata'):
if child.get('execute') == 'yes':
print "Execute something on child here"
1
内置的 etree
库可能会在这里帮上大忙。你可以这样做:
import xml.etree.ElementTree as ET
tree = ET.parse("my_file.xml") # iterparse would process one element at a time
root = tree.getroot()
for testdata in root.findall("testdata"):
if testdata.get("execute") == "yes":
command_list = []
for command in testdata.findall("command"):
command_list.append(command.text)
verify = testdata.find("verification").text
# Insert your code here.
另外,与你的代码 <verification> search ="verify" found ="yes" </verification>
相比,使用 <verification search ="verify" found ="yes" />
这样的格式会更容易解析。这样你就可以用 verification.get("search")
来获取信息。
更多信息可以在这里找到(我也从这里拿了一些代码):
https://docs.python.org/2/library/xml.etree.elementtree.html