我是python的新手所以请原谅..我已经解析了一个XML文件并插入到sqlite中就好了但是我现在需要从多个具有相同名称的元素(通道类别)中获取文本值插入一个sql列,如
somecategory1, somecategory2
这就是我现在正在做的事情
elif elem.tag == "channel":
cid = elem.get("id").replace("'", "")
title = elem.findtext("display-name")
chncategory = elem.findtext("channel-category")
..somecode..
..somecode..
result = Channel(cid, title, chncategory, logo, streamUrl, visible)
然后我称之为
c.execute('INSERT OR IGNORE INTO channels(id, title, chncategory, logo, stream_url, visible, weight, source) VALUES(?, ?, ?, ?, ?, ?, (CASE ? WHEN -1 THEN (SELECT COALESCE(MAX(weight)+1, 0) FROM channels WHERE source=?) ELSE ? END), ?)',
[channel.id, channel.title, channel.chncategory, channel.logo, channel.streamUrl, channel.visible, channel.weight,
self.source.KEY, channel.weight, self.source.KEY])
工作正常..但它只抓取FIRST通道类别元素,我需要抓住它们并添加到该列中,使其显示为
somecategory1, somecategory2, etc
我的xml看起来像这样
<tv info="blahblah">
<channel id="channel1">
<display-name lang="en">channel1</display-name>
<icon src="somewhere.png" />
<url>http://someurl.com</url>
<channel-category>somecategory1</channel-category>
<channel-category>somecategory2</channel-category>
</channel>
</tv>
我如何才能完成这项工作,而不只是抓住第一个值并将其放入列中,让它抓住所有并插入到那一列?
答案 0 :(得分:0)
怎么样,而不是
chncategory = elem.findtext("channel-category")
您使用:
In [5]: chncategory = ', '.join(map(lambda x: x.text, elem.findall("channel-category")))
In [6]: chncategory
Out[6]: 'somecategory1, somecategory2'