从 Python 编写 XML:Python 相当于 .NET XmlTextWriter?
我有一些 IronPython 代码,它使用 XmlTextWriter,它允许我编写代码,就像
self.writer = System.Xml.XmlTextWriter(filename, None)
self.writer.Formatting = Formatting.Indented
self.writer.WriteStartElement(name)
self.writer.WriteString(str(text))
self.writer.WriteEndElement()
...
self.writer.Close()
我想让我的代码在 Python 实现(CPython、IronPython 和 Jython)之间移植一样。 是否有一个流式 Python XML 编写器可以用于此目的,而无需使用打印语句,或者在将其写入文件之前构建整个 DOM 树?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我编写了一个名为 loxun 的模块来做到这一点: http://pypi.python.org/pypi/乐讯/。 它可以与 CPython 2.5 和 Jython 2.5 一起运行,但我从未尝试过使用 IronPython。
用法示例:
结果:
除其他功能外,它还可以在您编写时检测未对齐的标签,使用内存占用较小的流 API,支持 Unicode 并允许禁用漂亮打印。
I wrote a module named loxun to do just that: http://pypi.python.org/pypi/loxun/. It runs with CPython 2.5 and Jython 2.5, but I never tried it with IronPython.
Example usage:
And the result:
Among other features, it detects missalligned tags while you write, uses a streaming API with a small memory footprint, supports Unicode and allows to disable pretty printing.
我从未使用过您正在谈论的 .NET 实现,但听起来您将获得的最接近的是 Python 的 SAX 解析器(具体来说,XMLGenerator 类 -- 一些示例代码此处)。
I've never used the .NET implementation you're talking about, but it sounds like the closest you're going to get is Python's SAX parser (specifically, the XMLGenerator class -- some sample code here).
我编写了一个工具来促进从 Python 生成 XML(代码 和 < a href="http://www.from.bz/2009/03/28/announcing-xmlegant-for-python/" rel="nofollow noreferrer">教程)
I wrote a tool to facilitate XML generation from Python (code and tutorial)