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: 123 &l
Solution 1:
As pointed out in the comments by @kjhughes, the XML spec requires that a document must have a single root element.
from xml.etree import ElementTree as ET
node = ET.parse(Input_FilePath)
xml.etree.ElementTree.ParseError: junk after document element: line 4, column 0
You'll need to read the file manually and add the tags yourself:
from xml.etree import ElementTree as ET
with open(Input_FilePath) as f:
xml_string = '<X>' + f.read() + '</X>'
node = ET.fromstring(xml_string)
Solution 2:
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
Post a Comment for "How To Add A Root To An Existing XML Which Doesn't Have A Single Root Tag"