【发布时间】:2011-05-16 17:10:58
【问题描述】:
首先,这是我第一次尝试 Python,到目前为止它看起来很容易使用,尽管我仍然遇到了问题..
我正在尝试将 XML 文件更改为 rss-XML 原始 xml 源代码如下所示:
<news title="Random Title" date="Date and Time" subtitle="The article txt"></news>
它最终应该是这样的:
<item>
<pubDate>Date and Time</pubDate>
<title>Random Title</title>
<content:encoded>The article txt</content:encoded>
</item>
我正在尝试使用 python 和 BeautifulSoup 执行此操作,使用以下脚本
from BeautifulSoup import BeautifulSoup
import re
doc = [
'<news post_title="Random Title" post_date="Date and Time" post_content="The article txt">''</news></p>'
]
soup = BeautifulSoup(''.join(doc))
print soup.prettify()
posttitle = soup.news['post_title']
postdate = soup.news['post_date']
postcontent = soup.news['post_content']
print "<item>"
print "<pubDate>"
print postdate
print "</pubDate>"
print "<title>"
print posttitle
print "</title>"
print "<content:encoded>"
print postcontent
print "</content:encoded>"
print "</item>"
这里的问题是,它只检索最顶层的字符串 XML,而不是其他的。 任何人都可以给我一些解决这个问题的方向吗?
干杯:)
【问题讨论】:
-
你能给我们一些示例输出吗?您对问题的描述不是很清楚,因为只有一个 XML 字符串。
-
什么是“最上面的字符串”?
-
代码看起来完全符合您的要求。您是否有多个要解析的
项?
标签: python xml beautifulsoup xml-parsing