Python xml.etree.cElementTree.ElementTree() Examples
The following are 30
code examples of xml.etree.cElementTree.ElementTree().
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.cElementTree
, or try the search function
.
Example #1
Source File: tzconvert.py From ccs-pycalendar with Apache License 2.0 | 6 votes |
def parseWindowsAliases(self, aliases): try: with open(aliases) as xmlfile: xmlroot = XML.ElementTree(file=xmlfile).getroot() except (IOError, XMLParseError): raise ValueError("Unable to open or read windows alias file: {}".format(aliases)) # Extract the mappings try: for elem in xmlroot.findall("./windowsZones/mapTimezones/mapZone"): if elem.get("territory", "") == "001": if elem.get("other") not in self.links: self.links[elem.get("other")] = elem.get("type") else: print("Ignoring duplicate Windows alias: {}".format(elem.get("other"))) except (ValueError, KeyError): raise ValueError("Unable to parse windows alias file: {}".format(aliases))
Example #2
Source File: matstudio.py From VASPy with MIT License | 6 votes |
def update_name(self): """ 更新ElementTree中能量,力,作业路径等信息。 """ value = "" for key, attr in zip(['E', 'F', 'M'], ["energy", "force", "magnetism"]): data = getattr(self, attr, 0.0) value += "{}:{} ".format(key, data) value = value.strip() # Get current path. path = getcwd() value = "{} {}:{}".format(value, "P", path) for elem in self.tree.iter("SymmetrySystem"): elem.set("Name", value) break
Example #3
Source File: _serialization.py From azure-storage-python with MIT License | 6 votes |
def _convert_queue_message_xml(message_text, encode_function, key_encryption_key): ''' <?xml version="1.0" encoding="utf-8"?> <QueueMessage> <MessageText></MessageText> </QueueMessage> ''' queue_message_element = ETree.Element('QueueMessage') # Enabled message_text = encode_function(message_text) if key_encryption_key is not None: message_text = _encrypt_queue_message(message_text, key_encryption_key) ETree.SubElement(queue_message_element, 'MessageText').text = message_text # Add xml declaration and serialize try: stream = BytesIO() ETree.ElementTree(queue_message_element).write(stream, xml_declaration=True, encoding='utf-8', method='xml') output = stream.getvalue() finally: stream.close() return output
Example #4
Source File: prepostcondition.py From ccs-caldavtester with Apache License 2.0 | 6 votes |
def verify(self, manager, uri, response, respdata, args): # @UnusedVariable # If no status verification requested, then assume all 2xx codes are OK teststatus = args.get("error", []) statusCode = args.get("status", ["403", "409", "507"]) ignoreextras = args.get("ignoreextras", None) # status code could be anything, but typically 403, 409 or 507 if str(response.status) not in statusCode: return False, " HTTP Status Code Wrong: %d" % (response.status,) # look for pre-condition data if not respdata: return False, " No pre/post condition response body" try: tree = ElementTree(file=StringIO(respdata)) except Exception, ex: return False, " Could not parse XML: %s" % (ex,)
Example #5
Source File: xmlElementMatch.py From ccs-caldavtester with Apache License 2.0 | 6 votes |
def verify(self, manager, uri, response, respdata, args): # @UnusedVariable # Get arguments parent = args.get("parent", []) exists = args.get("exists", []) notexists = args.get("notexists", []) # status code must be 200, 207 if response.status not in (200, 207): return False, " HTTP Status Code Wrong: %d" % (response.status,) # look for response data if not respdata: return False, " No response body" # Read in XML try: tree = ElementTree(file=StringIO.StringIO(respdata)) except Exception, e: return False, " Response data is not xml data: %s" % (e,)
Example #6
Source File: document.py From SEM with MIT License | 6 votes |
def from_xml(cls, xml, chunks_to_load=None, load_subtypes=True, type_separator=u"."): if sem.misc.is_string(xml): data = ET.parse(xml) elif isinstance(xml, ET.ElementTree): data = xml elif isinstance(xml, type(ET.Element("a"))): # did not ind a better way to do this data = xml else: raise TypeError("Invalid type for loading XML-SEM document: {0}".format(type(xml))) root = data.getroot() if root.tag != "sem": raise ValueError("Not sem xml file type: '{0}'".format(root.tag)) doc_list = [] for document in list(root): doc_list.append(Document.from_xml(document)) return SEMCorpus(doc_list)
Example #7
Source File: matstudio.py From VASPy with MIT License | 6 votes |
def update(self): """ 根据最新数据获取更新ElementTree内容 """ if self.natom != len(self.data): raise UnmatchedDataShape( 'length of data is not equal to atom number.') elif self.natom != len(self.tf): raise UnmatchedDataShape( 'length of tf is not equal to atom number.') elif self.natom != len(self.atom_names): raise UnmatchedDataShape( 'length of atom names is not equal to atom number.') # atoms info self.update_atoms() # space group self.update_bases() # Thermodynamic info. self.update_name() return
Example #8
Source File: 2_data_to_pascal_xml.py From face-detection-ssd-mobilenet with Apache License 2.0 | 6 votes |
def newXMLPASCALfile(imageheight, imagewidth, path, basename): # print(filename) annotation = ET.Element("annotation", verified="yes") ET.SubElement(annotation, "folder").text = "images" ET.SubElement(annotation, "filename").text = basename ET.SubElement(annotation, "path").text = path source = ET.SubElement(annotation, "source") ET.SubElement(source, "database").text = "test" size = ET.SubElement(annotation, "size") ET.SubElement(size, "width").text = str(imagewidth) ET.SubElement(size, "height").text = str(imageheight) ET.SubElement(size, "depth").text = "3" ET.SubElement(annotation, "segmented").text = "0" tree = ET.ElementTree(annotation) # tree.write("filename.xml") return tree
Example #9
Source File: paypal.py From edx-analytics-pipeline with GNU Affero General Public License v3.0 | 6 votes |
def find_or_raise(node, child_name): """ Find the direct descendant of `node` with the tag `child_name`. If the no child is found with that tag, an error is raised. Args: node: an ElementTree.Element object representing a node in an XML document that is expected to have a child with the name specified by the `child_name` parameter. child_name: a string containing the name of the tag that is expected to be a direct descendant of `node`. Raises: PaypalMalformedResponseError: If the document does not have the expected structure. Returns: A reference to the child node when it is found. """ child = node.find(child_name) if child is None: raise PaypalMalformedResponseError( 'The required element "{}" was not found in the API response'.format(child_name), node ) return child
Example #10
Source File: cifar_prepare.py From ngraph-python with Apache License 2.0 | 6 votes |
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(imgSize) et.SubElement(root, 'Col').text = str(imgSize) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(imgSize * imgSize * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join( ['%e' % n for n in np.reshape(data, (imgSize * imgSize * 3))] ) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent=' '))
Example #11
Source File: e2m3u2bouquet.py From e2m3u2bouquet with GNU General Public License v3.0 | 6 votes |
def parse_map_xmltvsources_xml(self): """Check for a mapping override file and parses it if found """ self._xmltv_sources_list = {} mapping_file = self._get_mapping_file() if mapping_file: try: tree = ET.ElementTree(file=mapping_file) for group in tree.findall('.//xmltvextrasources/group'): group_name = group.attrib.get('id') urllist = [] for url in group: urllist.append(url.text) self._xmltv_sources_list[group_name] = urllist except Exception, e: msg = 'Corrupt override.xml file' print(msg) if DEBUG: raise msg
Example #12
Source File: paypal.py From edx-analytics-pipeline with GNU Affero General Public License v3.0 | 6 votes |
def find_text_or_raise(node, child_name): """ Extract the text from the direct descendant of `node` with the tag `child_name`. If the no child is found with that tag, an error is raised. Args: node: an ElementTree.Element object representing a node in an XML document that is expected to have a child with the name specified by the `child_name` parameter. child_name: a string containing the name of the tag that is expected to be a direct descendant of `node`. Raises: PaypalMalformedResponseError: If the document does not have the expected structure. Returns: The text contents of the child when it is found. """ text = node.findtext(child_name) if text is None: raise PaypalMalformedResponseError( 'The required element "{}" was not found in the API response'.format(child_name), node ) return text
Example #13
Source File: cifar_data_processing.py From batch-shipyard with MIT License | 6 votes |
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(IMGSIZE) et.SubElement(root, 'Col').text = str(IMGSIZE) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(IMGSIZE * IMGSIZE * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (IMGSIZE * IMGSIZE * 3))]) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent = ' '))
Example #14
Source File: arya.py From arya with Apache License 2.0 | 6 votes |
def isxmlorjson(s): try: json.loads(s) isjson = True except ValueError: isjson = False try: ETree.ElementTree(ETree.fromstring(s)) isxml = True except ETree.ParseError: isxml = False if isjson and isxml: raise ValueError('This file appears to be both XML and JSON. I am ' + 'confused. Goodbye') if isjson: return 'json' elif isxml: return 'xml' else: return None
Example #15
Source File: FeaturesToGPX.py From sample-gp-tools with Apache License 2.0 | 6 votes |
def featuresToGPX(inputFC, outGPX, zerodate, pretty): ''' This is called by the __main__ if run from a tool or at the command line ''' descInput = arcpy.Describe(inputFC) if descInput.spatialReference.factoryCode != 4326: arcpy.AddWarning("Input data is not projected in WGS84," " features were reprojected on the fly to create the GPX.") generatePointsFromFeatures(inputFC , descInput, zerodate) # Write the output GPX file try: if pretty: gpxFile = open(outGPX, "w") gpxFile.write(prettify(gpx)) else: gpxFile = open(outGPX, "wb") ET.ElementTree(gpx).write(gpxFile, encoding="UTF-8", xml_declaration=True) except TypeError as e: arcpy.AddError("Error serializing GPX into the file.") finally: gpxFile.close()
Example #16
Source File: paypal.py From edx-analytics-pipeline with GNU Affero General Public License v3.0 | 6 votes |
def from_xml(cls, root_node): """ Parse the status of the request from the response. This request status should be included in all responses. Args: root_node: an ElementTree.Element object representing the root node of the XML response. Returns: A valid response object. """ base_response_node = find_or_raise(root_node, 'baseResponse') params = { 'response_code': int(find_text_or_raise(base_response_node, 'responseCode')), 'response_message': find_text_or_raise(base_response_node, 'responseMsg') } params.update(cls.params_from_xml(root_node)) return cls(**params)
Example #17
Source File: a2p_fcdocumentreader.py From A2plus with GNU Lesser General Public License v2.1 | 6 votes |
def openDocument(self,fileName): self.clear() # check whether file exists or not... if not os.path.exists( fileName ): print (u"fcDocumentReader: file {} does not exist!".format(fileName)) return # # decompress the file f = zipfile.ZipFile(fileName,'r') xml = f.read('Document.xml') f.close() # # load the ElementTree self.tree = ET.ElementTree(ET.fromstring(xml)) # self.loadObjects()
Example #18
Source File: env.py From deeprl_signal_control with MIT License | 6 votes |
def collect_tripinfo(self): # read trip xml, has to be called externally to get complete file trip_file = self.output_path + ('%s_%s_trip.xml' % (self.name, self.agent)) tree = ET.ElementTree(file=trip_file) for child in tree.getroot(): cur_trip = child.attrib cur_dict = {} cur_dict['episode'] = self.cur_episode cur_dict['id'] = cur_trip['id'] cur_dict['depart_sec'] = cur_trip['depart'] cur_dict['arrival_sec'] = cur_trip['arrival'] cur_dict['duration_sec'] = cur_trip['duration'] cur_dict['wait_step'] = cur_trip['waitingCount'] cur_dict['wait_sec'] = cur_trip['waitingTime'] self.trip_data.append(cur_dict) # delete the current xml cmd = 'rm ' + trip_file subprocess.check_call(cmd, shell=True)
Example #19
Source File: sqldeveloper.py From LaZagneForensic with GNU Lesser General Public License v3.0 | 6 votes |
def get_passphrase(self, path): xml_name = u'product-preferences.xml' xml_file = None if os.path.exists(os.path.join(path, xml_name)): xml_file = os.path.join(path, xml_name) else: for p in os.listdir(path): if p.startswith('system'): new_directory = os.path.join(path, p) for pp in os.listdir(new_directory): if pp.startswith(u'o.sqldeveloper'): if os.path.exists(os.path.join(new_directory, pp, xml_name)): xml_file = os.path.join(new_directory, pp, xml_name) break if xml_file: tree = ET.ElementTree(file=xml_file) for elem in tree.iter(): if 'n' in elem.attrib.keys(): if elem.attrib['n'] == 'db.system.id': return elem.attrib['v']
Example #20
Source File: Main.py From strawpoll-voting-bot with MIT License | 6 votes |
def writeUsedProxy(self, proxyIp): if os.path.isfile(self.saveStateFile): # Read file tree = ET.parse(self.saveStateFile) # Get <root> tag root = tree.getroot() child = ET.Element("usedProxy") child.text = str(proxyIp) root.append(child) # Write to file tree.write(self.saveStateFile, encoding="UTF-8") else: # Create <root> tag root = ET.Element("article") # Get element tree tree = ET.ElementTree(root) # Write to file tree.write(self.saveStateFile, encoding="UTF-8") # Now write defined entry into file self.writeUsedProxy(proxyIp)
Example #21
Source File: eclipse.py From StarsAndClown with GNU General Public License v3.0 | 5 votes |
def GenerateClasspathFile(target_list, target_dicts, toplevel_dir, toplevel_build, out_name): '''Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.''' gyp.common.EnsureDirExists(out_name) result = ET.Element('classpath') def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, 'classpathentry') entry_element.set('kind', kind) entry_element.set('path', path) AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER']) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')]) ET.ElementTree(result).write(out_name)
Example #22
Source File: manager.py From ccs-caldavtester with Apache License 2.0 | 5 votes |
def readXML(self, serverfile, testfiles, ssl, all, moresubs={}): self.message("trace", "Reading Server Info from \"{s}\"".format(s=serverfile)) # Open and parse the server config file try: tree = ElementTree(file=serverfile) except ExpatError, e: raise RuntimeError("Unable to parse file '%s' because: %s" % (serverfile, e,)) # Verify that top-level element is correct
Example #23
Source File: eclipse.py From gyp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def GenerateClasspathFile(target_list, target_dicts, toplevel_dir, toplevel_build, out_name): '''Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.''' gyp.common.EnsureDirExists(out_name) result = ET.Element('classpath') def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, 'classpathentry') entry_element.set('kind', kind) entry_element.set('path', path) AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER']) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')]) ET.ElementTree(result).write(out_name)
Example #24
Source File: timeline.py From plex-mpv-shim with MIT License | 5 votes |
def SendTimelineToSubscriber(self, subscriber, timeline=None): subscriber.set_poll_evt() if subscriber.url == "": return True timelineXML = self.GetCurrentTimeLinesXML(subscriber, timeline) url = "%s/:/timeline" % subscriber.url log.debug("TimelineManager::SendTimelineToSubscriber sending timeline to %s" % url) tree = et.ElementTree(timelineXML) tmp = BytesIO() tree.write(tmp, encoding="utf-8", xml_declaration=True) tmp.seek(0) xmlData = tmp.read() # TODO: Abstract this into a utility function and add other X-Plex-XXX fields try: requests.post(url, data=xmlData, headers={ "Content-Type": "application/x-www-form-urlencoded", "Connection": "keep-alive", "Content-Range": "bytes 0-/-1", "X-Plex-Client-Identifier": settings.client_uuid }, timeout=5) return True except requests.exceptions.ConnectTimeout: log.warning("TimelineManager::SendTimelineToSubscriber timeout sending to %s" % url) return False except Exception: log.warning("TimelineManager::SendTimelineToSubscriber error sending to %s" % url) return False
Example #25
Source File: caldavtest.py From ccs-caldavtester with Apache License 2.0 | 5 votes |
def dofindall(self, original_request, collection, label=""): hrefs = [] req = request(self.manager) req.method = "PROPFIND" req.host = original_request.host req.port = original_request.port req.ruris.append(collection[0]) req.ruri = collection[0] req.headers["Depth"] = "1" if len(collection[1]): req.user = collection[1] if len(collection[2]): req.pswd = collection[2] req.data = data(self.manager) req.data.value = """<?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:prop> <D:getetag/> </D:prop> </D:propfind> """ req.data.content_type = "text/xml" result, _ignore_resulttxt, response, respdata = self.dorequest(req, False, False, label=label) if result and (response is not None) and (response.status == 207) and (respdata is not None): try: tree = ElementTree(file=StringIO(respdata)) except Exception: return () request_uri = req.getURI(self.manager.server_info) for response in tree.findall("{DAV:}response"): # Get href for this response href = response.findall("{DAV:}href") if len(href) != 1: return False, " Wrong number of DAV:href elements\n" href = href[0].text if href != request_uri: hrefs.append((href, collection[1], collection[2])) return hrefs
Example #26
Source File: client.py From plex-mpv-shim with MIT License | 5 votes |
def send_end(self): if self.completed: return response = BytesIO() tree = et.ElementTree(self.xmlOutput) tree.write(response, encoding="utf-8", xml_declaration=True) response.seek(0) xmlData = response.read() self.send_response(200) self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Expose-Headers", "X-Plex-Client-Identifier") self.send_header("X-Plex-Client-Identifier", settings.client_uuid) self.send_header("Content-type", "text/xml") # https://stackoverflow.com/questions/225086/ now = datetime.datetime.now() stamp = mktime(now.timetuple()) self.send_header("Date", formatdate( timeval=stamp, localtime=False, usegmt=True )) self.send_header("Content-Length", str(len(xmlData))) self.end_headers() self.wfile.write(xmlData) self.wfile.flush() self.completed = True #-------------------------------------------------------------------------- # URL Handlers #--------------------------------------------------------------------------
Example #27
Source File: sps_csj_preparator.py From abkhazia with GNU General Public License v3.0 | 5 votes |
def parse_xml(self, xml_file): """Parse raw transcript""" tree = ET.ElementTree(file=xml_file) talk = tree.getroot() talk_id = talk.attrib["TalkID"] speaker = talk.attrib["SpeakerID"] # make sure all speaker-ids have same length if len(speaker) < 4: speaker = "0"*(4-len(speaker)) + speaker else: assert len(speaker) == 4, talk_id # using kanji for 'male' gender = 'M' if talk.attrib["SpeakerSex"] == u"男" else 'F' spk_id = gender + speaker # Utterance level nb_utts = 0; nb_parsed_utts = 0; utts = {} for ipu in talk.iter("IPU"): nb_utts = nb_utts + 1 utt_id = spk_id + u"_" + talk_id + u"_" + ipu.attrib["IPUID"] channel = None utt_start = float(ipu.attrib["IPUStartTime"]) utt_stop = float(ipu.attrib["IPUEndTime"]) ipu_id = ipu.attrib["IPUID"] words, parse_successful = self.parse_ipu(ipu, ipu_id) if parse_successful: utts[utt_id] = Utt(words, utt_start, utt_stop, channel) nb_parsed_utts = nb_parsed_utts + 1 #proportion = 100.*nb_parsed_utts/float(nb_utts) #print('{:.2f} percent of {} utts successfully parsed'.format(proportion, # nb_utts)) return utts, nb_parsed_utts, nb_utts
Example #28
Source File: XMLCreator.py From codex-backend with MIT License | 5 votes |
def saveToFile(self, xml_node, file_name): tree = XML.ElementTree(xml_node) tree.write("../DB/metadata/" + str(file_name) + ".xml") return 0
Example #29
Source File: eclipse.py From gyp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def GenerateClasspathFile(target_list, target_dicts, toplevel_dir, toplevel_build, out_name): '''Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.''' gyp.common.EnsureDirExists(out_name) result = ET.Element('classpath') def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, 'classpathentry') entry_element.set('kind', kind) entry_element.set('path', path) AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER']) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')]) ET.ElementTree(result).write(out_name)
Example #30
Source File: _serialization.py From azure-cosmos-table-python with Apache License 2.0 | 5 votes |
def _convert_signed_identifiers_to_xml(signed_identifiers): if signed_identifiers is None: return '' sis = ETree.Element('SignedIdentifiers') for id, access_policy in signed_identifiers.items(): # Root signed identifers element si = ETree.SubElement(sis, 'SignedIdentifier') # Id element ETree.SubElement(si, 'Id').text = id # Access policy element policy = ETree.SubElement(si, 'AccessPolicy') if access_policy.start: start = access_policy.start if isinstance(access_policy.start, date): start = _to_utc_datetime(start) ETree.SubElement(policy, 'Start').text = start if access_policy.expiry: expiry = access_policy.expiry if isinstance(access_policy.expiry, date): expiry = _to_utc_datetime(expiry) ETree.SubElement(policy, 'Expiry').text = expiry if access_policy.permission: ETree.SubElement(policy, 'Permission').text = _str(access_policy.permission) # Add xml declaration and serialize try: stream = BytesIO() ETree.ElementTree(sis).write(stream, xml_declaration=True, encoding='utf-8', method='xml') except: raise finally: output = stream.getvalue() stream.close() return output