我是elementtree概念的初学者。
我刚学会了如何迭代xml文件中的所有标签。
for elem in root.iter():
print elem.tag, elem.attrib
现在,我想迭代特定标记的所有子元素。
我们将标记命名为"teams"
。
所以,我想迭代这个标签的所有孩子。
我怎样才能做到这一点?我正在使用python来解析xml文件。
答案 0 :(得分:1)
您可以使用simple XPath选择器表达式获取teams
的所有子元素:
for elem in root.findall(".//teams/*"):
print elem.tag, elem.attrib
答案 1 :(得分:0)
假设您有文件:
<强>的example.xml:强>
<example>
<sample>
<teams>
<team>
<id>1</id>
<name>example1</name>
</team>
<team>
<id>2</id>
<name>example2</name>
</team>
<team>
<id>3</id>
<name>example3</name>
</team>
</teams>
</sample>
<league>
<amateur>
<teams>
<team>
<id>1</id>
<name>example1</name>
</team>
<team>
<id>2</id>
<name>example2</name>
</team>
<team>
<id>3</id>
<name>example3</name>
</team>
</teams>
</amateur>
<pro>
<teams>
<team>
<id>1</id>
<name>example1</name>
</team>
<team>
<id>2</id>
<name>example2</name>
</team>
<team>
<id>3</id>
<name>example3</name>
</team>
</teams>
</pro>
</league>
</example>
现在使用Python你可以这样做:
from xml.dom import minidom
exampleDOM = minidom.parse('example.xml')
teams = exampleDOM.getElementsByTagName('teams')[0] # in sample section
for team in teams.getElementsByTagName('team'):
id = team.getElementsByTagName('id')[0].childNodes[0].toxml()
name = team.getElementsByTagName('name')[0].childNodes[0].toxml()
print('Team (%s): %s' % (id, name))
<强>输出:强>
Team (1): example1
Team (2): example2
Team (3): example3
使用ElementTree
库您可以更轻松地实现这一目标:
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()
for teams in root.iter('teams'):
for team in teams.iter('team'):
id = team.find('id').text
name = team.find('name').text
print('Team (%s): %s' % (id, name))
<强>输出:强>
Team (1): example1
Team (2): example2
Team (3): example3
Team (1): example1
Team (2): example2
Team (3): example3
Team (1): example1
Team (2): example2
Team (3): example3