![](/img/trans.png)
[英]Python: How to add a prefix to tags in an xml.etree.ElementTree
[英]parse .xml with prefix's on tags? xml.etree.ElementTree
我可以讀取標簽,除非有前綴。 我沒有運氣搜索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
media
是一個XML命名空間,必須先用xmlns:media="..."
定義它。 有關如何在lxml中定義用於XPath表達式的xml命名空間,請參閱http://lxml.de/xpathxslt.html#namespaces-and-prefixes 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.