所以在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>
?
答案 0 :(得分:1)
这是一个简单的生成器表达式,您可以使用它来查找包含text = 78
的数字元素的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字符串。
而且,仅供参考,使用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)