使用 python 创建一个简单的 XML 文件 [英] Creating a simple XML file using python

查看:66
本文介绍了使用 python 创建一个简单的 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在 python 中创建一个简单的 XML 文件,我有哪些选择?(图书馆明智)

What are my options if I want to create a simple XML file in python? (library wise)

我想要的 xml 看起来像:

The xml I want looks like:

<root>
 <doc>
     <field1 name="blah">some value1</field1>
     <field2 name="asdfasd">some vlaue2</field2>
 </doc>

</root>

推荐答案

如今,最流行(也非常简单)的选项是 ElementTree API,自 Python 2.5 起已包含在标准库中.

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

可用的选项有:

  • ElementTree(ElementTree 的基本纯 Python 实现.自 2.5 起成为标准库的一部分)
  • cElementTree(ElementTree 的优化 C 实现.自 2.5 起也在标准库中提供.自 3.3 起已弃用并作为自动内容折叠到常规 ElementTree 中.)
  • LXML(基于 libxml2.提供丰富的 ElementTree API 超集以及 XPath、CSS 选择器等)

以下是如何使用 in-stdlib cElementTree 生成示例文档的示例:

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

我已经对其进行了测试并且可以正常工作,但是我假设空格并不重要.如果你需要漂亮的"缩进,让我知道,我会查找如何做到这一点.(它可能是一个 LXML 特定的选项.我很少使用 stdlib 实现)

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

为了进一步阅读,这里有一些有用的链接:

For further reading, here are some useful links:

  • API docs for the implementation in the Python standard library
  • Introductory Tutorial (From the original author's site)
  • LXML etree tutorial. (With example code for loading the best available option from all major ElementTree implementations)

最后一点,cElementTree 或 LXML 应该足够快,可以满足您的所有需求(两者都是优化的 C 代码),但是如果您遇到需要挤出最后一点性能的情况,LXML 站点上的基准测试表明:

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML 在序列化(生成)XML 方面明显胜出
  • 作为实现正确的父遍历的副作用,LXML 在解析方面比 cElementTree 慢一点.

这篇关于使用 python 创建一个简单的 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆