【问题标题】:Python generating xml file by pythonPython通过python生成xml文件
【发布时间】:2016-08-01 06:47:40
【问题描述】:

下图是性能测试的结果。我的问题之一是:如何将结果传输到 XML 文件中?

我一直在尝试文件写入方法。但是,如果我需要解析的数据量很大怎么办?有没有更聪明的方法或插件?

到目前为止我的代码:

def generate_xml(jank_perc):

with open('jankyresult.xml','a') as f:
    f.write('<?xml version="1.0" ?>\n')
    f.write("<root>\n")
    f.write("   <doc>\n")
    f.write("      <Jankyframes>" + jank_perc + '%' + "</Jankyframes>\n")
    f.write("   </doc>\n")
    f.write("</root>\n")

我不想手动创建。我希望有一个更聪明的方法来做到这一点。感谢您的回答!

【问题讨论】:

  • 可以使用jinja2

标签: python xml python-2.7 xml-parsing ipython


【解决方案1】:

使用这个ElementTree。一个例子是,

from xml.etree import ElementTree, cElementTree
from xml.dom import minidom

root = ElementTree.Element('root')
child1 = ElementTree.SubElement(root, 'doc')
child1_1 = ElementTree.SubElement(child1, 'Jankyframes')
child1_1.text = jank_perc

print ElementTree.tostring(root)
tree = cElementTree.ElementTree(root) # wrap it in an ElementTree instance, and save as XML

t = minidom.parseString(ElementTree.tostring(root)).toprettyxml() # Since ElementTree write() has no pretty printing support, used minidom to beautify the xml.
tree1 = ElementTree.ElementTree(ElementTree.fromstring(t))

tree1.write("filename.xml",encoding='utf-8', xml_declaration=True)

【讨论】:

  • "tree = cElementTree.ElementTree(root)" 你能帮我解释一下这段代码吗?谢谢,我真的不知道它为什么在这里。
  • The cElementTree module is a C implementation of the ElementTree API, optimized for fast parsing and low memory use. On typical documents, cElementTree is 15-20 times faster than the Python version of ElementTree, and uses 2-5 times less memory 根据 effbot.org/zone/celementtree.htm 也在该代码前面添加了注释。
  • 感谢您回答我的问题。我注意到 ElementTree 的使用。
【解决方案2】:

看看yattag 库:

以 Python 方式生成 HTML 或 XML。纯 python 替代 web 模板引擎。可以用默认值和错误消息填充 HTML 表单。

这是基于您的代码示例的示例:

doc, tag, text = Doc().tagtext()

doc.asis('<?xml version="1.0"?>')

with tag('root'):
    with tag('doc'):
        with tag('Jankyframes'):
            text(jank_perc + '%')

with open('jankyresult.xml','a') as f:
    f.write(doc.getvalue())

根据您获取输入数据的方式(例如 listdict),您可以对其进行迭代并将结果写入 XML,同时仍保持代码可读性。

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    相关资源
    最近更新 更多