Search code examples
pythonxmlparse-error

How to add a root to an existing XML which doesn't have a single root tag


I'm having one XML file which doesn't have a single root tag. I want to add a new Root tag to this XML file.

Below is the existing XML:

<A>
    <Val>123</Val>
</A>

<B>
    <Val1>456</Val1>
</B>

Now I want to add a Root tag 'X', so the final XML will look like:

<X>
  <A>
     <Val>123</Val>
  </A>

  <B>
     <Val1>456</Val1>
  </B>
</X>

I've tried using the below python code:

from xml.etree import ElementTree as ET  
root = ET.parse(Input_FilePath).getroot()   
newroot = ET.Element("X")    
newroot.insert(0, root)    
tree = ET.ElementTree(newroot)    
tree.write(Output_FilePath)

But at the first line I'm getting the below error:

xml.etree.ElementTree.ParseError: junk after document element: line 4, column 4

Solution

  • I think your can do in without xml parsers. If your know that root tag missing, you can add it by such way.

    with open('test.xml', 'r') as f:
        data = f.read()
    
    with open('test.xml', 'w') as f:
        f.write("<x>\n" + data + "\n</x>")
        f.close()
    

    If dont know, your can check it by:

       import re
       if re.match(u"\s*<x>.*</x>", text, re.S) != None:
          #do something   
          pass