我可以读取标签,除非有前缀。我没有幸运地搜索 SO 以查找以前的问题。
我需要阅读media:content
。我尝试了 image = node.find("media:content")
。
Rss 输入:
<channel>
<title>Popular Photography in the last 1 week</title>
<item>
<title>foo</title>
<media:category label="Miscellaneous">photography/misc</media:category>
<media:content url="http://foo.com/1.jpg" height="375" width="500" medium="image"/>
</item>
<item> ... </item>
</channel>
我可以读取兄弟标签 title
。
from xml.etree import ElementTree
with open('cache1.rss', 'rt') as f:
tree = ElementTree.parse(f)
for node in tree.findall('.//channel/item'):
title = node.find("title").text
我一直在使用文档,但仍停留在“前缀”部分。
最佳答案
下面是一个使用 ElementTree 的 XML 命名空间的例子:
>>> x = '''\
<channel xmlns:media="http://www.w3.org/TR/html4/">
<title>Popular Photography in the last 1 week</title>
<item>
<title>foo</title>
<media:category label="Miscellaneous">photography/misc</media:category>
<media:content url="http://foo.com/1.jpg" height="375" width="500" medium="image"/>
</item>
<item> ... </item>
</channel>
'''
>>> node = ElementTree.fromstring(x)
>>> for elem in node.findall('item/{http://www.w3.org/TR/html4/}category'):
print elem.text
photography/misc
关于python - 解析带有前缀标签的 .xml? xml.etree.元素树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7949092/