Modify namespaces in a given xml document with lxml

前端 未结 1 1970
心在旅途
心在旅途 2020-12-21 21:36

I have an xml-document that looks like this:



        
相关标签:
1条回答
  • 2020-12-21 22:20

    All I want to do is change http://someurl/Oldschema to http://someurl/Newschema and http://someurl/Oldframework to http://someurl/Newframework and leave the remaining document unchanged.

    I'd do a simple textual search-and-replace operation. It's much easier than fiddling with XML nodes. Like this:

    with open("input.xml", "r") as infile, open("output.xml", "w") as outfile:
        data = infile.read()
        data = data.replace("http://someurl/Oldschema", "http://someurl/Newschema")
        data = data.replace("http://someurl/Oldframework", "http://someurl/Newframework")
        outfile.write(data)
    

    The other question that you were inspired by is about adding a new namespace (and keeping the old ones). But you are trying to modify existing namespace declarations. Creating a new root element and copying the child nodes does not work in this case.

    This line:

    new_root[:] = root[:]
    

    turns the children of the original root element into children of the new root element. But these child nodes are still associated with the old namespaces. So they have to be modified/recreated too. I guess it might be possible to come up with a reasonable way to do that, but I don't think you need it. Textual search-and-replace is good enough, IMHO.

    0 讨论(0)
提交回复
热议问题