简体   繁体   English

Python-搜索和替换XML文件中的内容

[英]Python - search and replace content in XML file

I have a requirement where I have a sample XML file with a well defined structure. 我有一个具有良好定义的结构的示例XML文件的要求。 I want to search of a tag/child in XML file, replace its text/value with some input file and save the changes to a new XML file preferably without effecting the input sample XML. 我想在XML文件中搜索标签/子项,将其文本/值替换为一些输入文件,并最好将更改保存到新的XML文件中,而最好不要影响输入样本XML。

I understand this can be achieved by a XML parser to traverse through to the child as intended. 我知道可以通过XML解析器按预期方式遍历到子级来实现。 But problem is that at the top of my XML file I have something like this 但是问题是在我的XML文件的顶部,我有类似的东西

<nc:data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">

I have written a python function as shown below to do it but I am failing to get the intended thing. 我已经编写了如下所示的python函数来执行此操作,但是我没有得到想要的东西。

def search_replace():
    replicate()        // This function just makes a tmp file from sample input XML to work on. 
    tree = et.parse("/path/to/file/tmp_file.xml")
    tree.find('nc:data/child1/child2/child3').text = 'test'
    tree.write("new_file.xml")

Please suggest what would be best approach to handle this. 请提出最好的处理方法。 I am not very python-skilled as of now !! 到目前为止,我还不是非常熟练的python !!

You need to create dictionary that map the prefix to namespace uri and pass that as additional parameter of find() : 您需要创建将前缀映射到名称空间uri的字典,并将其作为find()附加参数传递:

def search_replace():
    replicate()
    tree = et.parse("/path/to/file/tmp_file.xml")
    nsmap = {'nc': 'urn:ietf:params:xml:ns:netconf:base:1.0'}
    tree.find('nc:data/child1/child2/child3', nsmap).text = 'test'
    tree.write("new_file.xml")

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

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