繁体   English   中英

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

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

我有一个具有良好定义的结构的示例XML文件的要求。 我想在XML文件中搜索标签/子项,将其文本/值替换为一些输入文件,并最好将更改保存到新的XML文件中,而最好不要影响输入样本XML。

我知道可以通过XML解析器按预期方式遍历到子级来实现。 但是问题是在我的XML文件的顶部,我有类似的东西

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

我已经编写了如下所示的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")

请提出最好的处理方法。 到目前为止,我还不是非常熟练的python !!

您需要创建将前缀映射到名称空间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