使用python一次读取一个块的xml

时间:2014-08-26 19:58:09

标签: python python-2.7

我是Python的新手,拥有以下XML。我希望能够读取每个testdata块(一次一个)并能够读取testdata块中的子节点。基本上,我想读取文件并根据行号(行= 1)一次取一个testdata块,if(execute = no)然后跳过整个测试数据块。接下来去阅读testdata的子项并获取行的值。接下来,读取获取搜索的值和找到的值。一旦阅读了所有内容,我将编写自己的代码来做任何我想做的事情。一旦完成该代码,我们将返回with row = 2并读取与row1中相同的内容并运行我自己编写的代码,依此类推,直到读取所有testdata块。我正在使用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 个答案:

答案 0 :(得分: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

答案 1 :(得分:-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"