首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在yattag中复制xml.etree示例

在yattag中复制xml.etree示例
EN

Stack Overflow用户
提问于 2018-05-31 23:06:46
回答 1查看 502关注 0票数 1

我正在尝试在使用xml.etreeyattag之间进行选择。yattag似乎有更简洁的语法,但我不能100%复制this xml.etree example

代码语言:javascript
复制
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))

它会返回

代码语言:javascript
复制
<?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的尝试

代码语言:javascript
复制
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)

它返回:

代码语言:javascript
复制
<?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代码更短、更简单(我认为),但我不知道如何:

在开头添加XML版本标记(解决方法是doc.asis)

  • Create a comment (解决方法是doc.asis)

  • Escape "字符。xml.etree&quot;

  • Add tail text替换了它-但我不确定我为什么需要这个。

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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.

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50627432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档