2011-10-31 1 views
3

Je peux lire les balises, sauf s'il y a un préfixe. Je n'ai pas de chance de chercher SO pour une question précédente.parse .xml avec le préfixe des balises? xml.etree.ElementTree

J'ai besoin de lire media:content. J'ai essayé image = node.find("media:content"). entrée 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> 

Je peux lire une étiquette de frères et soeurs 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 

J'utilise les docs, encore collé sur la partie « préfixe ».

Répondre

4

Voici un exemple d'utilisation de XML avec espaces de noms ElementTree:

>>> 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