我有一个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>