在yattag中复制xml.etree示例

时间:2018-05-31 15:06:46

标签: python xml xml.etree yattag

我正在尝试使用xml.etreeyattagyattag似乎有更简洁的语法,但我无法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 &quot;tail&quot; text.
  <child_with_entity_ref>This &amp; 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 &amp; that
    </child_with_entity_ref>
</top>

所以yattag代码更短更简单(我认为),但我无法弄清楚如何:

  1. 在开始时自动添加XML版本标记(解决方法为doc.asis
  2. 创建评论(解决方法为doc.asis
  3. 转义"个字符。 xml.etree已将其替换为&quot;
  4. 添加尾文 - 但我不确定为什么我需要这个。
  5. 我的问题是,我可以比使用yattag更好地完成上述4点吗?

    注意:我正在构建XML以与this api进行交互。

1 个答案:

答案 0 :(得分:1)

对于1 et 2,doc.asis是最好的方法。

对于3,您应该使用text('And "tail" text.')而不是asis。这将逃避需要转义的角色。但请注意,"方法实际上并未转义text字符。 这个是正常的。 "只有在xml或html属性中出现时才需要进行转义,并且您不需要在文本节点内对其进行转义。 text方法转义需要在文本节点内转义的字符。这些是&amp;,&lt;和&gt;字符。 (来源:http://www.yattag.org/#the-text-method

我不明白4。