我正在尝试在使用xml.etree
和yattag
之间进行选择。yattag
似乎有一个更简洁的语法,但我无法100%复制this ^{
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))
它回来了
^{pr2}$我的尝试使用yattag
:
返回:
<?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
代码更短更简单(我想),但我无法想出如何:
doc.asis
)doc.asis
)"
字符。xml.etree
将其替换为"
我的问题是,我能比使用yattag
更好地完成以上4点吗?在
注意:我正在构建与this api交互的XML。在
对于1et2,
doc.asis
是继续进行的最佳方法。在对于3,您应该使用
text('And "tail" text.')
,而不是使用asis
。这将转义需要转义的字符。{{cd5}实际上并不是由cd5}转义的。 这很正常。只有当"
出现在xml或html属性中时,才需要对其进行转义,而不需要在文本节点中对其进行转义。text
方法转义需要在文本节点内转义的字符。这些是&;、<;和>;字符。(来源:http://www.yattag.org/#the-text-method)我不明白4。在
相关问题 更多 >
编程相关推荐