首页 > 解决方案 > Adding a comment to an element and making the element text appear after the comment

问题描述

I want to save an XML file with a comment, but even if I add the comment before adding the text, the comment appears after the text in the output. My code and output is below.

def save_xml(data):
    root = etree.Element('root')
    student_xml = etree.ElementTree(root)
    student = etree.SubElement(root,'students')
    student.append(etree.Comment('\n学生信息表\n\"id\": [名字,数学,语文,英语]\n'))
    student.text = str(data)
    file = open('student.xml', 'w',encoding='utf-8')
    file.write(etree.tounicode(student_xml.getroot()))
    file.close()


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

And I want the output like below.

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

标签: pythonxmllxml

解决方案


添加文本作为tail评论节点的。

student = etree.SubElement(root, 'students')
comment = etree.Comment('\n学生信息表\n\"id\": [名字,数学,语文,英语]\n')
comment.tail = "\n" + str(data)
student.append(comment)

tail属性包含紧跟在元素之后的文本(注释是一种特殊类型的元素节点)。

另见https://lxml.de/tutorial.html#elements-contain-texthttp://infohost.nmt.edu/~shipman/soft/pylxml/web/etree-view.html


如果漂亮的打印很重要,您可以做一些事情:

  1. 使用pretty_print=True.

  2. 用于pprint.pformat()格式化data字典。

  3. 在几个地方添加一些额外的空格。

完整示例:

from lxml import etree
from pprint import pformat

data = {
    "1" : ["张三", 150, 120, 100],
    "2" : ["李四", 90, 99, 95],
    "3" : ["王五", 60, 66, 68]
}

root = etree.Element('root')

student = etree.SubElement(root, 'students')
student.text = "\n"
comment = etree.Comment('\n     学生信息表\n     \"id\": [名字,数学,语文,英语]\n')
comment.tail = "\n" + pformat(data, width=35) + "\n"
student.append(comment)

etree.ElementTree(root).write("students.xml", pretty_print=True,
                              encoding="UTF-8", xml_declaration=True)

student.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>

推荐阅读