Define An Xml Schema From A Txt File With Python Script And Store It In A Single Xml File
I am trying to write an xml schema using python from a .txt file. I tried the following code but it didn't read the values in lines of the text. The data is like: # Fil
Solution 1:
A few changes, plus the fix. The changes are:
- Using a context manager to ensure the input file gets closed correctly.
- Using the fact that iterating a file yields each line in
turn (rather than
f.readlines()
). - Combining the splitting and stripping of the parts of the line into one statement.
The fix is to set the text
value for the subelements just after they are created.
import xml.etree.ElementTree as ET
root = ET.Element('root')
root.text = '\n' # newline before the celldata elementwith open("C:/baseball.txt") as f:
for l in f:
elems = [ x.strip() for x in l.split(":") ]
if len(elems) == 4:
playerdata = ET.SubElement(root, "playerdata")
playerdata.text = '\n'
playerdata.tail = '\n\n'
team = ET.SubElement(playerdata, "team")
team.text = elems[0]
player = ET.SubElement(playerdata, "player")
player.text = elems[1]
salary = ET.SubElement(playerdata, "salary")
salary.text = elems[2]
position = ET.SubElement(playerdata, "position")
position.text = elems[3]
ET.dump(root)
tree = ET.ElementTree(root)
tree.write("test1.xml", encoding='utf-8', xml_declaration=True)
Post a Comment for "Define An Xml Schema From A Txt File With Python Script And Store It In A Single Xml File"