如何在元素开始处的xml子元素中添加注释

狗他

我正在使用lxml尝试输出以下xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <students>
        <!-- 
            学生信息表
            "id" : [名字, 数学, 语文, 英文]
        -->
        {
        "1" : ["张三", 150, 120, 100],
        "2" : ["李四", 90, 99, 95],
        "3" : ["王五", 60, 66, 68]
        }
    </students>
</root> 

这是我的代码,但是输出不正确:

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')

输出的xml是这样的;注释不在元素中<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>

请帮助我解决我做错了什么以及如何进行。

杰克·弗莱汀

尝试这种方式:

students = """<?xml version="1.0" encoding="UTF-8"?>
<root>
    <students>        
        </students>
    </root> """

student_txt = """{ "1" : ["张三", 150, 120, 100], "2" : ["李四", 90, 99, 95], "3" : ["王五", 60, 66, 68]} """
    
from lxml import etree
doc = etree.XML(students.encode())

destination = doc.xpath('//students')[0]
destination.text=''    
new_comment = etree.Comment(student_txt)    
new_comment.tail = "\n"+student_txt

destination.insert(0, new_comment)
print(etree.tostring(doc).decode())

输出:

<root>
    <students><!--{ "1" : ["张三", 150, 120, 100], "2" : ["李四", 90, 99, 95], "3" : ["王五", 60, 66, 68]} -->
{ "1" : ["张三", 150, 120, 100], "2" : ["李四", 90, 99, 95], "3" : ["王五", 60, 66, 68]} </students>
</root>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章