我正在尝试在使用xml.etree和之间进行选择yattag。yattag似乎有更简洁的语法,但我不能 100% 复制这个xml.etree例子:
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
top = Element('top')
comment = Comment('Generated for PyMOTW')
top.append(comment)
child = SubElement(top, 'child')
child.text = 'This child contains text.'
child_with_tail = SubElement(top, 'child_with_tail')
child_with_tail.text = 'This child has regular text.'
child_with_tail.tail = 'And "tail" text.'
child_with_entity_ref = SubElement(top, 'child_with_entity_ref')
child_with_entity_ref.text = 'This & that'
print(tostring(top))
from xml.etree import ElementTree
from xml.dom import minidom
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
print(prettify(top))
返回
<?xml version="1.0" ?>
<top>
<!--Generated for PyMOTW-->
<child>This child contains text.</child>
<child_with_tail>This child has regular text.</child_with_tail>
And "tail" text.
<child_with_entity_ref>This & that</child_with_entity_ref>
</top>
我尝试使用yattag:
from yattag import Doc
from yattag import indent
doc, tag, text, line = Doc().ttl()
doc.asis('<?xml version="1.0" ?>')
with tag('top'):
doc.asis('<!--Generated for PyMOTW-->')
line('child', 'This child contains text.')
line('child_with_tail', 'This child has regular text.')
doc.asis('And "tail" text.')
line('child_with_entity_ref','This & that')
result = indent(
doc.getvalue(),
indentation = ' ',
newline = '\r\n',
indent_text = True
)
print(result)
返回:
<?xml version="1.0" ?>
<top>
<!--Generated for PyMOTW-->
<child>
This child contains text.
</child>
<child_with_tail>
This child has regular text.
</child_with_tail>
And "tail" text.
<child_with_entity_ref>
This & that
</child_with_entity_ref>
</top>
所以yattag代码更短更简单(我认为),但我不知道如何:
- 在开始时自动添加 XML 版本标记(解决方法是
doc.asis) - 创建评论(解决方法是
doc.asis) - 逃离
"角色。xml.etree将其替换为" - 添加尾部文本 --- 但我不确定我为什么需要这个。
我的问题是我能比使用 4 点做得更好yattag吗?
注意:我正在构建 XML 以与此 api交互。