将 python 对象转换为 XML 表示 [英] Convert python object to XML representation

查看:38
本文介绍了将 python 对象转换为 XML 表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中,我有一些需要在 xml 文件中表示的对象.将项目对象转换为项目的 xml 表示的最简单/最简单的方法是什么?我应该使用什么 python 库?

In my database I have some objects that need to be represented in xml file. What is the simplest/easiest way to convert the item objects into a xml representation of the items? What python library should I use?

<items>
    <item>
        <picture><![CDATA[foo.jpg]]></picture>
        <title><![CDATA[Foo]]></title>
        <link><![CDATA[http://www.foo.com]]></link>
    <color><![CDATA[red]]></color>
    </item>

    <item>
        <picture><![CDATA[baz.jpg]]></picture>
        <title><![CDATA[Baz]]></title>
        <link><![CDATA[http://www.baz.com]]></link>
    <color><![CDATA[blue]]></color>
    </item>
</items>

推荐答案

使用 string.Template 类.

import string
item_template = string.Template( """<item>
    <picture><![CDATA[$a]]></picture>
    <title><![CDATA[$b]]></title>
    <link><![CDATA[$c]]></link>
<color><![CDATA[$d]]></color>
</item>""")
item = item_template( a="foo.jpg", b="Foo", c="http://www.foo.com", d="red" )

然后您应该能够按如下方式构建项目列表:

You should be able to then build a list of items as follows:

item_list= string.Template( "<items>$item_list</items>" )
item_list.substitute( item_list= "\n".join( some_list_of_item_strings ) )

那种东西可以从非 XML 片段构建适当的 XML 文档.

That kind of thing can build up proper XML documents from non-XML pieces.

这篇关于将 python 对象转换为 XML 表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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