Python 包含特定元素的Eddited XML文件
因此,在python中,我需要读写XML数据库。我已经完成了读取部分,但是我很难找到只将数据写入具有特定元素的节点的方法 这应该可以澄清问题Python 包含特定元素的Eddited XML文件,python,xml,Python,Xml,因此,在python中,我需要读写XML数据库。我已经完成了读取部分,但是我很难找到只将数据写入具有特定元素的节点的方法 这应该可以澄清问题 <team> <number>78</number> <matches_played>0</matches_played> <matches_played>0</matches_played> <start_position>1
<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>
78
0
0
1.
0
0
0
0
0
0
0
0
0
0
0
0
0
195
0
0
1.
0
0
0
0
0
0
0
0
0
0
0
0
0
正如您所看到的,这两个都是
,它们都有一个
,我如何只在中编辑元素
78
?这里有一个简单的生成器表达式,您可以使用它来查找包含number元素的team元素,该元素的text=78
:
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)
您喜欢哪种解析器?@alecxe我使用
xml.etree.ElementTree
我可以交换lxml和ElementTree吗?@ExcelledProducts我已经包含了使用lxml
的解决方案,请检查。对于您的ElementTree,我如何将其放入循环中以便设置文本?@ExcelledProducts您想更改什么?就像我只想编辑78中的hig_goals_Make_tel一样