如何在dexml中为标签添加属性?

时间:2013-10-18 07:30:21

标签: python xml xml-serialization

我正在使用这个Python XML序列化库dexml。我无法弄清楚如何将属性放在我从对象生成的xml中的某些标记上。我仔细阅读了文档,除非我无法阅读,否则我无法找到一个很好的解释。

这是涉及的代码。

import dexml
import urllib2
from dexml import fields
from bs4 import BeautifulSoup

class Section(dexml.Model):
    section = fields.String()
    entries = fields.List(fields.String(tagname="Entry"))
    # Add something for href here, maybe?

class AtoZ(dexml.Model):
    list = fields.List(Section)

def makeSoup(url):
    return BeautifulSoup(urllib2.urlopen(url).read())

def main():
    soup = makeSoup("http://www.somewebsite.com")

    sectionList = []

    # You might wonder about the length of this; I *could* split it up
    # into variables to make it shorter. Also, the chaining is because
    # the 'li' I want are only inside of a <ul class="Nav_fm>".
    for li in soup.find('ul', {'class':"Nav_fm"}).find_all('li', {'class':"MenuLevel_0"}):
    atzSection = Section()
    atzSection.section = li.a.string

    for innerLi in li.find_all('li', {'class':"MenuLevel_1"}):
        atzSection.entries.append(innerLi.a.string)
        # Somehow store innlerLi.a['href'] in atzSection

    sectionList.append(atzSection)

    atzList = AtoZ(list=sectionList)

    f = open("C:\\atoz.xml", "w")
    f.write(atzList.render(pretty=True))
    f.close()

if __name__ == '__main__':
    main()

以下是生成的XML。

<?xml version="1.0" ?>
<AtoZ>
    <Section section="#">
        <Entry>...</Entry>
        <Entry>...</Entry>
        <Entry>...</Entry>
        <Entry>...</Entry>
    </Section>
    ...
    <Section section="Z">
        <Entry>...</Entry>
        <Entry>...</Entry>
        <Entry>...</Entry>
        <Entry>...</Entry>
    </Section>
</AtoZ>

我希望每个<Entry href="...">...</Entry>都有<Entry>

1 个答案:

答案 0 :(得分:1)

尝试将Section.entries重新定义为条目列表,如下所示:

class Entry(dexml.Model):
    href = fields.String() 
    ...

class Section(dexml.Model):
    section = fields.String()
    entries = fields.List(fields.Model(Entry), tagname='Entry')

查看dexml test code - 除了文档所描述的内容之外,还有许多关于如何使用它的好插图。