python - 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>
解决方案
添加文本作为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-text和http://infohost.nmt.edu/~shipman/soft/pylxml/web/etree-view.html。
如果漂亮的打印很重要,您可以做一些事情:
使用
pretty_print=True
.用于
pprint.pformat()
格式化data
字典。在几个地方添加一些额外的空格。
完整示例:
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>
推荐阅读
- javascript - 我的 javascript 阻止我的代码工作
- bash - 如何在登录后 5 秒自动退出 ssh?
- c# - YouTube Data V3 API 无法识别用于重定向 uri 的 localhost url,为什么?
- swift - Swift 4 领域 Swift 对象
- android - TextView 不会将点击传递给父级
- android - 如何在 Android Studio 3.2 Preview Canary 18 中创建新的 android 项目?
- python - Python3中元组的不变性
- javascript - 从对象渲染 React 组件
- symfony - Symfony 3:在实体 ORM 表前缀中使用 parameters.yml 中的参数
- javascript - 有没有办法通过 vscode 将代码注入网站