这是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
?
答案 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>