首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有特定元素的编辑XML文件

具有特定元素的编辑XML文件
EN

Stack Overflow用户
提问于 2014-03-19 19:09:57
回答 1查看 27关注 0票数 0

因此,在python中,我需要读写XML数据库。我已经完成了读取部分,但我很难找到只将数据写入具有特定元素的节点的方法。

这应该能把事情弄清楚

代码语言:javascript
复制
 <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>中编辑元素?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-19 19:22:12

下面是一个简单的生成器表达式,您可以使用它查找包含带有text = 78的number元素的team元素

代码语言:javascript
复制
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支持:

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22515877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档