Python xml.etree.ElementTree._namespace_map() Examples

The following are 13 code examples of xml.etree.ElementTree._namespace_map(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.etree.ElementTree , or try the search function .
Example #1
Source File: Objects.py    From IFIscripts with MIT License 6 votes vote down vote up
def _ET_tostring(e):
    """Between Python v2 and v3, there are some differences in the ElementTree library's tostring() behavior.  One, the method balks at the "unicode" encoding in v2.  Two, in 2, the XML prototypes output with every invocation.  This method serves as a wrapper to deal with those issues, plus another issue where ET.tostring prints repeated xmlns declarations (observed on reading and writing a DFXML file twice in the same process).  The repeated prints appear to be from a lack of inspection of existing namespace declarations in the attributes dictionary."""
    retval = None
    if sys.version_info[0] < 3:
        tmp = ET.tostring(e, encoding="UTF-8")
        if tmp[0:2] == "<?":
            #Trim away first line; it's an XML prototype.  This only appears in Python 2's ElementTree output.
            retval = tmp[ tmp.find("?>\n")+3 : ]
        else:
            retval = tmp
    else:
        retval = ET.tostring(e, encoding="unicode")
    container_end = retval.index(">")
    for (uri, prefix) in list(ET._namespace_map.items()):
        if prefix == "":
            xmlns_attr_name = "xmlns"
        else:
            xmlns_attr_name = "xmlns:" + prefix
        xmlns_attr_string = '%s="%s"' % (xmlns_attr_name, uri)
        xmlns_attr_tally = retval.count(xmlns_attr_string, 0, container_end)
        if xmlns_attr_tally > 1:
            _logger.warning("ET.tostring() printed a repeated xmlns declaration: %r.  Trimming %d repetition(s)." % (xmlns_attr_string, xmlns_attr_tally-1))
            container_string = retval[ : container_end+1 ]
            retval = container_string.replace(xmlns_attr_string, "", xmlns_attr_tally-1) + retval[ container_end+1 : ]
    return retval 
Example #2
Source File: digiglobe_api.py    From FloodMapsWorkshop with Apache License 2.0 6 votes vote down vote up
def GetFeaturesInBbox(bbox):
	#featureType = "DigitalGlobe:CollectedContent"	
	featureType = "DigitalGlobe:FinishedFeature"	
	url 		= "%s&request=GetFeature&typeName=%s&srsName=EPSG:4326&Bbox=%s" % (wfs2_url, featureType, ",".join(str(x) for x in bbox))
	print url
	
	request 		= urllib2.Request(url)
	base64string 	= base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
	request.add_header("Authorization", "Basic %s" % base64string) 
	
	#ET._namespace_map["http://www.digitalglobe.com"] = 'DigitalGlobe'
	#ET._namespace_map["http://www.opengis.net/gml"] = 'gml'
	
	try:
		response 	= urllib2.urlopen(request)
		print "Info:", response.info()
		
		result 		= response.read()
		print result
		
		
	except urllib2.HTTPError as e:
		print '*** WFS Server error', e.code(), e.read() 
Example #3
Source File: test_xml_etree.py    From BinderFilter with MIT License 5 votes vote down vote up
def __enter__(self):
        from xml.etree import ElementTree
        self._nsmap = ElementTree._namespace_map
        self._path_cache = ElementTree.ElementPath._cache
        # Copy the default namespace mapping
        ElementTree._namespace_map = self._nsmap.copy()
        # Copy the path cache (should be empty)
        ElementTree.ElementPath._cache = self._path_cache.copy()
        self.checkwarnings.__enter__() 
Example #4
Source File: test_xml_etree.py    From BinderFilter with MIT License 5 votes vote down vote up
def __exit__(self, *args):
        from xml.etree import ElementTree
        # Restore mapping and path cache
        ElementTree._namespace_map = self._nsmap
        ElementTree.ElementPath._cache = self._path_cache
        self.checkwarnings.__exit__(*args) 
Example #5
Source File: test_xml_etree.py    From oss-ftp with MIT License 5 votes vote down vote up
def __enter__(self):
        from xml.etree import ElementTree
        self._nsmap = ElementTree._namespace_map
        self._path_cache = ElementTree.ElementPath._cache
        # Copy the default namespace mapping
        ElementTree._namespace_map = self._nsmap.copy()
        # Copy the path cache (should be empty)
        ElementTree.ElementPath._cache = self._path_cache.copy()
        self.checkwarnings.__enter__() 
Example #6
Source File: test_xml_etree.py    From oss-ftp with MIT License 5 votes vote down vote up
def __exit__(self, *args):
        from xml.etree import ElementTree
        # Restore mapping and path cache
        ElementTree._namespace_map = self._nsmap
        ElementTree.ElementPath._cache = self._path_cache
        self.checkwarnings.__exit__(*args) 
Example #7
Source File: xml_.py    From ryu with Apache License 2.0 5 votes vote down vote up
def register_namespace(prefix, uri):
        from xml.etree import ElementTree
        # cElementTree uses ElementTree's _namespace_map, so that's ok
        ElementTree._namespace_map[uri] = prefix 
Example #8
Source File: Objects.py    From IFIscripts with MIT License 5 votes vote down vote up
def add_namespace(self, prefix, url):
        """In case of conflicting namespace definitions, first definition wins."""
        #_logger.debug("self._namespaces.keys() = %r." % self._namespaces.keys())
        if prefix not in self._namespaces.keys():
            #_logger.debug("Registering namespace: %r, %r." % (prefix, url))
            self._namespaces[prefix] = url
            ET.register_namespace(prefix, url)
            #_logger.debug("ET namespaces after registration: %r." % ET._namespace_map) 
Example #9
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __enter__(self):
        from xml.etree import ElementTree
        self._nsmap = ElementTree._namespace_map
        self._path_cache = ElementTree.ElementPath._cache
        # Copy the default namespace mapping
        ElementTree._namespace_map = self._nsmap.copy()
        # Copy the path cache (should be empty)
        ElementTree.ElementPath._cache = self._path_cache.copy()
        self.checkwarnings.__enter__() 
Example #10
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __exit__(self, *args):
        from xml.etree import ElementTree
        # Restore mapping and path cache
        ElementTree._namespace_map = self._nsmap
        ElementTree.ElementPath._cache = self._path_cache
        self.checkwarnings.__exit__(*args) 
Example #11
Source File: digiglobe_api.py    From FloodMapsWorkshop with Apache License 2.0 5 votes vote down vote up
def FindCollectedFeatures(bbox):
	featureType = "CollectedContent"
	#featureType = "DigitalGlobe:FinishedFeature"	
		
	url = "%s&request=GetFeature&typeName=%s&srsName=EPSG:4326&bbox=%s" % (wfs2_url, featureType, ",".join(str(x) for x in bbox))
	print url
	
	request 		= urllib2.Request(url)
	base64string 	= base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
	request.add_header("Authorization", "Basic %s" % base64string) 
	
	#ET._namespace_map["http://www.digitalglobe.com"] = 'DigitalGlobe'
	#ET._namespace_map["http://www.opengis.net/gml"] = 'gml'
	
	try:
		response 	= urllib2.urlopen(request)
		#print "Info:", response.info()
		
		result 		= response.read()
		
		print result
		
		#root 		= ET.fromstring(result)
		#for child in root:
		#	print child.tag, child.attrib
		#namespaces 	= {'gml': 'http://www.opengis.net/gml', 'DigitalGlobe': "http://www.digitalglobe.com"} # add more as needed
		
		#posList 	= root.find('gml:featureMembers/DigitalGlobe:FinishedFeature/DigitalGlobe:geometry/gml:Polygon/gml:exterior/gml:LinearRing/gml:posList', namespaces).text
		#print posList
		#arr			= posList.split(" ")
		#bbox		= [ float(arr[1]), float(arr[0]), float(arr[5]), float(arr[4])]
		#print bbox
		#return bbox
		
	except urllib2.HTTPError as e:
		print '*** WFS Server error', e.code(), e.read() 
Example #12
Source File: digiglobe_api.py    From FloodMapsWorkshop with Apache License 2.0 5 votes vote down vote up
def FindFeature(identifier):
	featureType = "DigitalGlobe:FinishedFeature"	
	#url = "%s&request=GetFeature&typeName=%s&BBOX=-64.8,32.3,-64.7,32.4&srsName=EPSG:4326" % (wfs_url, featureType)
	#url = "%s&request=GetFeature&typeName=%s&BBOX=30.250383448012,-97.7684708569195,30.3119534076606,-97.7092977813448&WIDTH=3000&HEIGHT=3000&srsName=EPSG:4326" % (wfs_url, featureType)
	url = "%s&request=GetFeature&typeName=%s&srsName=EPSG:4326&CQL_Filter=featureId='%s'" % (wfs_url, featureType, identifier)
	#print url
	
	request 		= urllib2.Request(url)
	base64string 	= base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
	request.add_header("Authorization", "Basic %s" % base64string) 
	
	#ET._namespace_map["http://www.digitalglobe.com"] = 'DigitalGlobe'
	#ET._namespace_map["http://www.opengis.net/gml"] = 'gml'
	
	try:
		response 	= urllib2.urlopen(request)
		#print "Info:", response.info()
		
		result 		= response.read()
		root 		= ET.fromstring(result)
		#for child in root:
		#	print child.tag, child.attrib
		namespaces 	= {'gml': 'http://www.opengis.net/gml', 'DigitalGlobe': "http://www.digitalglobe.com"} # add more as needed
		
		posList 	= root.find('gml:featureMembers/DigitalGlobe:FinishedFeature/DigitalGlobe:geometry/gml:Polygon/gml:exterior/gml:LinearRing/gml:posList', namespaces).text
		#print posList
		arr			= posList.split(" ")
		bbox		= [ float(arr[1]), float(arr[0]), float(arr[5]), float(arr[4])]
		#print bbox
		return bbox
		
	except urllib2.HTTPError as e:
		print '*** WFS Server error', e.code(), e.read() 
Example #13
Source File: test_xml_etree.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def test_main(module=None):
    # When invoked without a module, runs the Python ET tests by loading pyET.
    # Otherwise, uses the given module as the ET.
    if module is None:
        module = pyET

    global ET
    ET = module

    test_classes = [
        ModuleTest,
        ElementSlicingTest,
        BasicElementTest,
        BadElementTest,
        BadElementPathTest,
        ElementTreeTest,
        IOTest,
        ParseErrorTest,
        XIncludeTest,
        ElementTreeTypeTest,
        ElementFindTest,
        ElementIterTest,
        TreeBuilderTest,
        XMLParserTest,
        BugsTest,
        ]

    # These tests will only run for the pure-Python version that doesn't import
    # _elementtree. We can't use skipUnless here, because pyET is filled in only
    # after the module is loaded.
    if pyET is not ET:
        test_classes.extend([
            NoAcceleratorTest,
            ])

    # Provide default namespace mapping and path cache.
    from xml.etree import ElementPath
    nsmap = pyET._namespace_map
    # Copy the default namespace mapping
    nsmap_copy = nsmap.copy()
    # Copy the path cache (should be empty)
    path_cache = ElementPath._cache
    ElementPath._cache = path_cache.copy()
    try:
        support.run_unittest(*test_classes)
    finally:
        from xml.etree import ElementPath
        # Restore mapping and path cache
        nsmap.clear()
        nsmap.update(nsmap_copy)
        ElementPath._cache = path_cache
        # don't interfere with subsequent tests
        ET = None