python如何更新xml内容_Python:如何编辑XML文件的元素?

我有一个XML文件,该文件包含许多命名元素,每个元素下面都有几个节点:

myVal

myMethod

myVal

myMethod

我想搜索这个XML文件,并且如果该名称搜索值以select ARG开头(在我的示例中,第一个值是select ARG:write),我想创建这个新的命名元素,但是这次是选择ARG的值:应选择写ARG:写.这是我尝试过的:

from xml.dom import minidom

xamlfile = r'C:\file.xml'

newxamlfile = r'C:\new.xml'

dom = minidom.parse(xamlfile)

# Fetch the desired elements in the tree.

res = dom.getElementsByTagName('name')

# Loop through all.

for element in res:

search_name_value = element.getAttribute('search')

# Filter for the attribute and value.

if search_name_value.startswith('select ARG:'):

# In case of match,replace.

element.setAttribute('search_name',search_name_value.replace('select ARG:','selected ARG:'))

# Store the file.

with open(newxamlfile,'w') as f:

f.write(dom.toxml())

在这里,我替换了所需的字符串,而不添加新的字符串,而是编辑所需的元素,而不是创建新的元素并将其添加到文件中.

有什么建议怎么做?

更新

这是我之前的文件:

myVal

myMethod

myVal

myMethod

这就是我想要我的文件的方式:

myVal

myMethod

myVal

myMethod

myVal

myMethod

myVal

myMethod

编辑

根据@DirtyBit的建议:

xmldoc = minidom.parse(xamlfile)

tags = xmldoc.getElementsByTagName("name")

for item in tags:

str = item.attributes["search"].value

if 'select ARG' in str:

item.attributes["search"].value = item.attributes["search"].value.replace('select ARG','selected ARG')

with open(xamlfile,"a+") as f:

xmldoc.writexml(f)

这工作正常,但我有2个问题:

>如您所见,我添加了if语句,因为我想复制并仅在选择ARG的值中创建新节点(并将其替换为所选的ARG),而不复制没有达到此条件的其他节点.

>在新XML文件的中间,我有这行:

< / element>< element>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值