1

我正在尝试在使用xml.etree和之间进行选择yattagyattag似乎有更简洁的语法,但我不能 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 &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. 添加尾部文本 --- 但我不确定我为什么需要这个。

我的问题是我能比使用 4 点做得更好yattag吗?

注意:我正在构建 XML 以与此 api交互。

4

1 回答 1

2

对于 1 和 2,doc.asis是进行的最佳方式。

对于 3,您应该使用text('And "tail" text.')而不是使用asis. 这将转义需要转义的字符。但请注意,"该方法实际上并未转义该字符text。这很正常。如果它出现"在 xml 或 html 属性中,则唯一需要对其进行转义,并且您不需要在文本节点内对其进行转义。该text方法转义文本节点内需要转义的字符。这些是 &、< 和 > 字符。(来源:http ://www.yattag.org/#the-text-method )

没看懂 4

于 2018-06-02T19:01:37.940 回答