I have a txt file contains more than 100 thousands lines, and for each line I want to create a XML tree. BUT all lines are sharing the same root.
Here the txt file:
LIBRARY:
1,1,1,1,the
1,2,1,1,world
2,1,1,2,we
2,5,2,1,have
7,3,1,1,food
The desired output:
<LIBRARY>
<BOOK ID ="1">
<CHAPTER ID ="1">
<SENT ID ="1">
<WORD ID ="1">the</WORD>
</SENT>
</CHAPTER>
</BOOK>
<BOOK ID ="1">
<CHAPTER ID ="2">
<SENT ID ="1">
<WORD ID ="1">world</WORD>
</SENT>
</CHAPTER>
</BOOK>
<BOOK ID ="2">
<CHAPTER ID ="1">
<SENT ID ="1">
<WORD ID ="2">we</WORD>
</SENT>
</CHAPTER>
</BOOK>
<BOOK ID ="2">
<CHAPTER ID ="5">
<SENT ID ="2">
<WORD ID ="1">have</WORD>
</SENT>
</CHAPTER>
</BOOK>
<BOOK ID ="7">
<CHAPTER ID ="3">
<SENT ID ="1">
<WORD ID ="1">food</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
I use Element tree for converting txt file to xml file, this is the code I run
def expantree():
lines = txtfile.readlines()
for line in lines:
split_line = line.split(',')
BOOK.set( 'ID ', split_line[0])
CHAPTER.set( 'ID ', split_line[1])
SENTENCE.set( 'ID ', split_line[2])
WORD.set( 'ID ', split_line[3])
WORD.text = split_line[4]
tree = ET.ElementTree(Root)
tree.write(xmlfile)
Okay, the code is working but i didnt get the desired output, I got the following:
<LIBRARY>
<BOOK ID ="1">
<CHAPTER ID ="1">
<SENT ID ="1">
<WORD ID ="1">the</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
<LIBRARY>
<BOOK ID ="1">
<CHAPTER ID ="2">
<SENT ID ="1">
<WORD ID ="1">world</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
<LIBRARY>
<BOOK ID ="2">
<CHAPTER ID ="1">
<SENT ID ="1">
<WORD ID ="2">we</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
<LIBRARY>
<BOOK ID ="2">
<CHAPTER ID ="5">
<SENT ID ="2">
<WORD ID ="1">have</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
<LIBRARY>
<BOOK ID ="7">
<CHAPTER ID ="3">
<SENT ID ="1">
<WORD ID ="1">food</WORD>
</SENT>
</CHAPTER>
</BOOK>
</LIBRARY>
How to unify the tree root , so instead of getting many root tag I get one root tag?