如何将 Python 对象更改为 XML? [英] How can I change a Python object into XML?

查看:32
本文介绍了如何将 Python 对象更改为 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将 Python 对象转换为 XML 数据.我尝试过 lxml,但最终不得不编写自定义代码来将我的对象保存为 xml,这并不完美.

I am looking to convert a Python object into XML data. I've tried lxml, but eventually had to write custom code for saving my object as xml which isn't perfect.

我正在寻找更像 pyxser 的东西.不幸的是,pyxser xml 代码看起来与我需要的不同.

I'm looking for something more like pyxser. Unfortunately pyxser xml code looks different from what I need.

例如我有自己的班级人

Class Person:
    name = ""
    age = 0
    ids = []

我想把它转换成看起来像 xml 代码

and I want to covert it into xml code looking like

<Person>
    <name>Mike</name>
    <age> 25 </age>
    <ids>
        <id>1234</id>
        <id>333333</id>
        <id>999494</id>
   </ids>
</Person>

我在 lxml.objectify 中没有找到任何接受对象并返回 xml 代码的方法.

I didn't find any method in lxml.objectify that takes object and returns xml code.

推荐答案

Best 是相当主观的,我不确定在不了解您的需求的情况下是否可以说什么是最好的.但是 Gnosis以前 被推荐用于将 Python 对象序列化为 XML,因此您可能想从它开始.

Best is rather subjective and I'm not sure it's possible to say what's best without knowing more about your requirements. However Gnosis has previously been recommended for serializing Python objects to XML so you might want to start with that.

来自 Gnosis 主页:

From the Gnosis homepage:

Gnosis Utils 包含几个用于 XML 处理的 Python 模块,以及其他常用的工具:

Gnosis Utils contains several Python modules for XML processing, plus other generally useful tools:

  • xml.pickle(将对象序列化为 XML 或从 XML 序列化)
  • API 与标准 pickle 模块兼容)
  • xml.objectify(将任意 XML 文档转换为 Python 对象)
  • xml.validity(通过 DTD 或 Schema 强制执行 XML 有效性约束)
  • xml.indexer(全文索引/搜索)
  • 更多...

另一个选项是lxml.objectify.

这篇关于如何将 Python 对象更改为 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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