通过指定limit来从xml获取节点

时间:2014-03-20 13:47:53

标签: python-2.7 xpath xml-parsing elementtree

这是xml

<Faculty>
    <facultyMember>
        <FirstName>A</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>B</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>G</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>H</FirstName>
    </facultyMember>

</Faculty>

我希望通过提供nodes来获取此xml index

例如如果我向3提供6,则输出应该是,

    <facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>

如何使用etree python

执行此操作

1 个答案:

答案 0 :(得分:1)

我们的想法是找到所有facultyMember项并使用python的列表切片:

from xml.etree import ElementTree as ET


data = """<Faculty>
    <facultyMember>
        <FirstName>A</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>B</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>G</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>H</FirstName>
    </facultyMember>

</Faculty>"""

tree = ET.fromstring(data)
begin, end = 3, 6

for element in tree.findall('.//facultyMember')[begin - 1: end]:
    print ET.tostring(element).strip()

打印:

<facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
<facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
<facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
<facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>