我正在尝试在使用xml.etree和yattag之间进行选择。yattag似乎有更简洁的语法,但我不能100%复制this xml.etree example
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用"
我的问题是,我能比使用yattag做得更好吗?
注意:我正在构建与this api交互的XML。
发布于 2018-06-03 03:01:38
对于1 et 2,doc.asis是继续进行的最佳方式。
对于3,您应该使用text('And "tail" text.')而不是asis。这将转义需要转义的字符。但是请注意,text方法实际上并没有对"字符进行转义。这很正常。只有当"出现在xml或html属性中时,才需要对其进行转义,而您不需要在文本节点中对其进行转义。text方法对文本节点内需要转义的字符进行转义。这些是&、<和>字符。(来源:http://www.yattag.org/#the-text-method )
我不明白4.
https://stackoverflow.com/questions/50627432
复制相似问题