Я пытаюсь выбрать между использованием xml.etree
и yattag
.yattag
, кажется, имеет более краткий синтаксис, но я не могу 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 "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
заменил его на "
- Добавить хвостовой текст --- но я не уверен, зачем мне это нужно.
Мой вопрос: могу ли я сделатьвыше на 4 пункта лучше, чем я использовал yattag
?
Примечание: я создаю XML для взаимодействия с этим API .