复制xml.etreeyattag中的示例

2024-09-28 22:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在使用xml.etreeyattag之间进行选择。yattag似乎有一个更简洁的语法,但我无法100%复制this ^{} 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))

它回来了

^{pr2}$

我的尝试使用yattag

^{3}$

返回:

<?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 version标记(解决方法是doc.asis
  2. 创建注释(解决方法是doc.asis
  3. 转义"字符。xml.etree将其替换为&quot;
  4. 加上尾文——但我不知道为什么我需要这个。在

我的问题是,我能比使用yattag更好地完成以上4点吗?在

注意:我正在构建与this api交互的XML。在


Tags: textfromimportrefchildtopwithxml
1条回答
网友
1楼 · 发布于 2024-09-28 22:28:51

对于1et2,doc.asis是继续进行的最佳方法。在

对于3,您应该使用text('And "tail" text.'),而不是使用asis。这将转义需要转义的字符。{{cd5}实际上并不是由cd5}转义的。 这很正常。只有当"出现在xml或html属性中时,才需要对其进行转义,而不需要在文本节点中对其进行转义。 text方法转义需要在文本节点内转义的字符。这些是&;、<;和>;字符。(来源:http://www.yattag.org/#the-text-method

我不明白4。在

相关问题 更多 >