get the namespaces from xml with python ElementTree

前端 未结 2 1035
栀梦
栀梦 2020-12-11 09:22

I use python 2.7 with the lib ElementTree.

I can\'t use lxml lib.

I need to get the namespaces in a string namespace_string. In order to fill my

2条回答
  •  无人及你
    2020-12-11 09:49

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

提交回复
热议问题