因此,在python中,我需要读写XML数据库。我已经完成了读取部分,但我很难找到只将数据写入具有特定元素的节点的方法。
这应该能把事情弄清楚
<team>
<number>78</number>
<matches_played>0</matches_played>
<matches_played>0</matches_played>
<start_position>1</start_position>
<preloaded_ball>0</preloaded_ball>
<high_goals_made_auto>0</high_goals_made_auto>
<low_goals_made_auto>0</low_goals_made_auto>
<shots_missed_auto>0</shots_missed_auto>
<hot_goal_bonus_auto>0</hot_goal_bonus_auto>
<moved_bonus_auto>0</moved_bonus_auto>
<high_goals_made_tel>0</high_goals_made_tel>
<low_goals_made_tel>0</low_goals_made_tel>
<shots_missed_tel>0</shots_missed_tel>
<balls_received_tel>0</balls_received_tel>
<balls_passed_tel>0</balls_passed_tel>
<truss_shots_tel>0</truss_shots_tel>
<catches_tel>0</catches_tel>
</team>
<team>
<number>195</number>
<matches_played>0</matches_played>
<matches_played>0</matches_played>
<start_position>1</start_position>
<preloaded_ball>0</preloaded_ball>
<high_goals_made_auto>0</high_goals_made_auto>
<low_goals_made_auto>0</low_goals_made_auto>
<shots_missed_auto>0</shots_missed_auto>
<hot_goal_bonus_auto>0</hot_goal_bonus_auto>
<moved_bonus_auto>0</moved_bonus_auto>
<high_goals_made_tel>0</high_goals_made_tel>
<low_goals_made_tel>0</low_goals_made_tel>
<shots_missed_tel>0</shots_missed_tel>
<balls_received_tel>0</balls_received_tel>
<balls_passed_tel>0</balls_passed_tel>
<truss_shots_tel>0</truss_shots_tel>
<catches_tel>0</catches_tel>
</team> 正如您所看到的,两者都是<team>,而且它们都有一个<number>,我如何只在<number>78</number>中编辑元素?
发布于 2014-03-19 19:22:12
下面是一个简单的生成器表达式,您可以使用它查找包含带有text = 78的number元素的team元素
tree = ET.fromstring(data)
team = next(team for team in tree.iter('team')
for number in team.iter('number')
if number.text == '78')
team.find('.//high_goals_made_tel').text = "I've changed"
print ET.tostring(tree)其中data是您的xml。
而且,仅仅是FYI,使用lxml的解决方案看起来要容易得多,因为它有完全的xpath支持:
from lxml import etree
from lxml.etree import XMLParser
data = """..."""
tree = etree.fromstring(data, parser=XMLParser())
team = tree.xpath('.//number[text()="78"]/..')[0]
team.find('high_goals_made_tel').text = "I've changed"
print etree.tostring(tree)https://stackoverflow.com/questions/22515877
复制相似问题