2017-11-21 2 views
0

Ich habe die andere Frage über Parsing XML with namespace in Python via 'ElementTree' untersucht und die XML.etree.ElementTree-Dokumentation überprüft. Das Problem, das ich habe, ist zugegebenermaßen ähnlich, also fühlen Sie sich frei, dieses als Doppel zu markieren, aber ich kann es nicht herausfinden.Parsing XML-Attribut mit Namespace python3

Die Codezeile ich Probleme habe mit ist

instance_alink = root.find('{http://www.w3.org/2005/Atom}link') 

Mein Code ist wie folgt:

import xml.etree.cElementTree as ET 

tree = ET.parse('../../external_data/rss.xml') 
root = tree.getroot() 

instance_title = root.find('channel/title').text 
instance_link = root.find('channel/link').text 
instance_alink = root.find('{http://www.w3.org/2005/Atom}link') 
instance_description = root.find('channel/description').text 
instance_language = root.find('channel/language').text 
instance_pubDate = root.find('channel/pubDate').text 
instance_lastBuildDate = root.find('channel/lastBuildDate').text 

Die XML-Datei:

<?xml version="1.0" encoding="windows-1252"?> 
<rss version="2.0"> 
    <channel> 
    <title>Filings containing financial statements tagged using the US GAAP or IFRS taxonomies.</title> 
    <link>http://www.example.com</link> 
    <atom:link href="http://www.example.com" rel="self" type="application/rss+xml" xmlns:atom="http://www.w3.org/2005/Atom"/> 
    <description>This is a list of up to 200 of the latest filings containing financial statements tagged using the US GAAP or IFRS taxonomies, updated every 10 minutes.</description> 
    <language>en-us</language> 
    <pubDate>Mon, 20 Nov 2017 20:20:45 EST</pubDate> 
    <lastBuildDate>Mon, 20 Nov 2017 20:20:45 EST</lastBuildDate> 
.... 

Die Attribute I‘ m versuchen zu erreichen sind in Zeile 6; so 'href', 'Typ', usw.

<atom:link href="http://www.example.com" rel="self" type="application/rss+xml" xmlns:atom="http://www.w3.org/2005/Atom"/> 

Offensichtlich habe ich versucht

instance_alink = root.find('{http://www.w3.org/2005/Atom}link').attrib 

aber das nicht funktioniert weil es keine ist ein. Mein Gedanke ist, dass es nach Kindern sucht, aber es gibt keine. Ich kann die Attribute in den anderen Zeilen in XML aber nicht diese aus irgendeinem Grund greifen. Ich habe auch mit ElementTree und lxml gespielt (aber lxml wird aus irgendeinem Grund unter Windows nicht richtig geladen)

Jede Hilfe wird sehr geschätzt, da die Dokumentation spärlich erscheint.

Antwort

0

konnte mich mit

alink = root.find('channel/{http://www.w3.org/2005/Atom}link').attrib 

das Problem lösen, ist, dass ich für den Tag {http://www.w3.org/2005/Atom}link auf dem gleiche Niveau von <channel> war auf der Suche, die, natürlich, gab es nicht.