在python中用sax2生成xml [英] generate xml with sax2 in python

查看:126
本文介绍了在python中用sax2生成xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据模型或一个类的对象,我需要通过读取一个XML文件来初始化它,或者从头开始创建这个对象并将其输出到一个xml文件中。以前,我只是使用python的字符串操作来读取xml(file.read + string.find)并写入xml(file.write),而没有检查错误。

现在我正在考虑使用Sax2来做到这一点。我知道如何去阅读,但写的不是很清楚。它看起来像萨克斯2是用于案件,当有一个原始的XML,你想输出一定的修改后。在我的情况下,我想我的数据模型输出到XML,根本没有原始的XML。我不知道萨克斯2是好还是适合这个,或者我应该继续使用我的老方法。使用python从/向XML输入/输出类对象的更好方法是什么?该类非常简单(只是一个列表信息,即根 - >儿童 - >孙辈)的列表收集和小尺寸。



感谢您的任何建议。

解决方案

尝试pythonic XML处理方式: ElementTree



使用xml.etree.ElementTree.ElementTree.write()
$ b


write(file ,encoding =us-ascii,xml_declaration = None,method =xml)



将元素树写入文件XML。文件是一个文件名或打开的文件对象写入。编码 1 是输出编码(默认是US-ASCII)。 xml_declaration控制是否应将XML声明添加到文件中。永远使用False,永远为True,仅当US-ASCII或UTF-8(默认值为None)时才使用False。方法是xml,html或text(默认是xml)。返回一个已编码的字符串。

从文本文件加载 ElementTree / p>

 >>> from xml.etree.ElementTree import ElementTree 
>>> tree = ElementTree()
>>> tree.parse(index.xhtml)


I have a data model or an object from a class, and I need to initialize it by reading from an xml file, or create this object from scratch and output it to an xml file. Previously, I simply use string operations from python to read xml (file.read + string.find) and write xml (file.write), without error checking.

Now I am thinking to use Sax2 to do this. I know how to do it for the read, but not very clear about write. It looks like the sax2 is used for the case when there is an original xml and you want to output after certain modifications. In my case I want to output my data model to xml, with no original xml at all. I wonder if sax2 is good or suitable for this or I should keep using my old way. What is the better way to input/output a class object from/to XML with python? The class is very simple (just a list collection of a list information, i.e., root -> children -> grandchildren) and small size.

Thanks for any suggestions.

解决方案

Try the pythonic XML processing way: ElementTree.

Generating XML output is easy with`xml.etree.ElementTree.ElementTree.write().

write(file, encoding="us-ascii", xml_declaration=None, method="xml")

Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding 1 is the output encoding (default is US-ASCII). xml_declaration controls if an XML declaration should be added to the file. Use False for never, True for always, None for only if not US-ASCII or UTF-8 (default is None). method is either "xml", "html" or "text" (default is "xml"). Returns an encoded string.

Example loading ElementTree object from text file:

>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")

这篇关于在python中用sax2生成xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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