get the namespaces from xml with python ElementTree

一个人想着一个人 提交于 2019-11-29 12:10:05

The code for creating a dictionary with all the declared namespaces can be made quite simple. This is all that is needed:

import xml.etree.ElementTree as ET

my_namespaces = dict([node for _, node in ET.iterparse('file.xml',
                                                        events=['start-ns'])])

You don't need to use StringIO or open(). Just provide the XML filename as an argument to iterparse().

Each item provided by iterparse() is an (event, (prefix, namespace-uri)) tuple. The start-ns event is not described in the Python 2.7 documentation of iterparse (but it is mentioned in the corresponding Python 3 documentation).


Note: the code above works in CPython and Jython, but not in IronPython. See https://github.com/IronLanguages/main/issues/968.

You should pass the contents of the xml file in ET.iterparse() instead of string my_schema.

Change your code to:

from io import StringIO
import xml.etree.ElementTree as ET

xml = "file.xml"
f = open(xml, "r")
xml_data = unicode(f.read() , "utf-8") 
my_namespaces = dict([node for _, node in ET.iterparse(StringIO(xml_data), events=['start-ns'])])

from pprint import pprint
pprint(my_namespaces)

Output:

{'': 'http://www.adv-online.de/namespaces/adv/gid/6.0',
 u'adv': 'http://www.adv-online.de/namespaces/adv/gid/6.0',
 u'gco': 'http://www.isotc211.org/2005/gco',
 u'gmd': 'http://www.isotc211.org/2005/gmd',
 u'gml': 'http://www.opengis.net/gml/3.2',
 u'ogc': 'http://www.adv-online.de/namespaces/adv/gid/ogc',
 u'ows': 'http://www.opengis.net/ows',
 u'wfs': 'http://www.adv-online.de/namespaces/adv/gid/wfs',
 u'wfsext': 'http://www.adv-online.de/namespaces/adv/gid/wfsext',
 u'xlink': 'http://www.w3.org/1999/xlink',
 u'xsd': 'http://www.w3.org/2001/XMLSchema',
 u'xsi': 'http://www.w3.org/2001/XMLSchema-instance'}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!