Accesso attribuiscono XMLNS con Python ElementTree?
-
21-09-2019 - |
Domanda
Come si può accedere NS attribuisce attraverso l'utilizzo ElementTree?
Con la seguente:
<data xmlns="http://www.foo.net/a" xmlns:a="http://www.foo.net/a" book="1" category="ABS" date="2009-12-22">
Quando provo ad root.get ( 'xmlns') torno Nessuno, categoria e data vanno bene, Qualsiasi aiuto apprezzato ..
Nessuna soluzione corretta
Altri suggerimenti
Credo element.tag
è quello che stai cercando. Si noti che il tuo esempio non è presente una barra finale, quindi è sbilanciato e non analizzare. Ho aggiunto uno nel mio esempio.
>>> from xml.etree import ElementTree as ET
>>> data = '''<data xmlns="http://www.foo.net/a"
... xmlns:a="http://www.foo.net/a"
... book="1" category="ABS" date="2009-12-22"/>'''
>>> element = ET.fromstring(data)
>>> element
<Element {http://www.foo.net/a}data at 1013b74d0>
>>> element.tag
'{http://www.foo.net/a}data'
>>> element.attrib
{'category': 'ABS', 'date': '2009-12-22', 'book': '1'}
Se si desidera solo conoscere le xmlns URI, è possibile dividere fuori con una funzione come:
def tag_uri_and_name(elem):
if elem.tag[0] == "{":
uri, ignore, tag = elem.tag[1:].partition("}")
else:
uri = None
tag = elem.tag
return uri, tag
Per molto di più su spazi dei nomi e nomi qualificati in elementtree, vedere esempi di effbot .
un'occhiata alla documentazione namespace effbot / Esempi; in particolare il href="http://effbot.org/zone/element-namespaces.htm" rel="noreferrer"> parse_map funzione Tuttavia, che aggiunge l'attributo ns_map a tutti gli elementi. Per le mie esigenze, ho trovato che volevo una mappa globale di tutti gli spazi dei nomi utilizzati per rendere più facile elemento di guardare in alto e non hardcoded. Ecco quello che mi si avvicinò con: Con questo si può analizzare un file XML e ottenere un dict con le mappature di namespace. Quindi, se si dispone di un file XML come il seguente ( "my.xml"): Sarete in grado di utilizzare i namepaces XML e ottenere informazioni per elementi come dc: creator : import elementtree.ElementTree as ET
def parse_and_get_ns(file):
events = "start", "start-ns"
root = None
ns = {}
for event, elem in ET.iterparse(file, events):
if event == "start-ns":
if elem[0] in ns and ns[elem[0]] != elem[1]:
# NOTE: It is perfectly valid to have the same prefix refer
# to different URI namespaces in different parts of the
# document. This exception serves as a reminder that this
# solution is not robust. Use at your own peril.
raise KeyError("Duplicate prefix with different URI found.")
ns[elem[0]] = "{%s}" % elem[1]
elif event == "start":
if root is None:
root = elem
return ET.ElementTree(root), ns
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:dc="http://purl.org/dc/elements/1.1/"\
>
<feed>
<item>
<title>Foo</title>
<dc:creator>Joe McGroin</dc:creator>
<description>etc...</description>
</item>
</feed>
</rss>
>>> tree, ns = parse_and_get_ns("my.xml")
>>> ns
{u'content': '{http://purl.org/rss/1.0/modules/content/}',
u'dc': '{http://purl.org/dc/elements/1.1/}'}
>>> item = tree.find("/feed/item")
>>> item.findtext(ns['dc']+"creator")
'Joe McGroin'
Prova questo:
import xml.etree.ElementTree as ET
import re
import sys
with open(sys.argv[1]) as f:
root = ET.fromstring(f.read())
xmlns = ''
m = re.search('{.*}', root.tag)
if m:
xmlns = m.group(0)
print(root.find(xmlns + 'the_tag_you_want').text)