简体   繁体   English

在Python中读取XML文件,在一行中搜索键并替换值

[英]Read XML file in Python, search for key in a line and replace value

I have an XML file that looks like this! 我有一个看起来像这样的XML文件!

<?xml version="1.0"?>
 <root>    
  <child>    
   <add key="setid" value=".\print\data1" />    
    <add key="getid" value=".\print\data2" />    
    <add key="holdingid" value=".\print\data3" />    
   </child>    
 </root>

I want to read a line in the XML, search for a key match and replace a value in that line with .\\donotpritnnt\\data1 我想读取XML中的一行,搜索键匹配项,并用.\\donotpritnnt\\data1替换该行中的值

I can do this in NANT using XMLPOKE and xpath. 我可以使用XMLPOKE和xpath在NANT中做到这一点。 Tried this with dict, list (replacing with positionID), split (not good enough code to show here) 尝试使用dict,list(替换为positionID),split(没有足够的代码在此处显示)

How can I solve this? 我该如何解决?

Assuming your XML code is in test.xml in the working directory. 假设您的XML代码在工作目录的test.xml中。

new_content = []
with open("test.xml") as f:
    content = f.readlines()
    for line in content:
        newline = line
        if 'key="setid"' in line:
            newline =  line[:line.find("value=")] + 'value=".\donotpritnnt\data1" />\n'
        new_content += [newline]
with open('test.xml', 'w') as f:
    for line in new_content:
        f.write(line)

Its not the nicest way, but it works for the example you provided, and may also be extentable since it iterates over the file and looks at each line. 它不是最好的方法,但是它适用于您提供的示例,并且可能会扩展,因为它会遍历文件并查看每一行。 Further improvements may probably by using regex etc. 可能通过使用正则表达式等进行进一步的改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM