I am using lxml in an attempt to to output the following xml code:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<students>
<!--
学生信息表
"id" : [名字, 数学, 语文, 英文]
-->
{
"1" : ["张三", 150, 120, 100],
"2" : ["李四", 90, 99, 95],
"3" : ["王五", 60, 66, 68]
}
</students>
</root>
This is my code, but the output is not correct:
from lxml import etree
with open('student.txt', 'r') as f:
data = f.read()
root = etree.Element("root")
child1 = etree.SubElement(root, "students" )
child1.addprevious(etree.Comment('学生信息表 \n "id" : [名字, 数学, 语文, 英文]'))
child1.text = str(data)
# write to file:
tree = etree.ElementTree(root)
tree.write('student.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')
The output xml is like this; comment is not in element <students>:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<!--学生信息表
"id" : [名字, 数学, 语文, 英文]-->
<students>{
"1":["张三",150,120,100],
"2":["李四",90,99,95],
"3":["王五",60,66,68]
}
</students>
</root>
Please help me out on what I am doing wrong and how to proceed.