我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xml.etree.cElementTree.tostring()。
def __SendDataPart(data, connection): """This method is deprecated, use atom.http._send_data_part""" deprecated('call to deprecated function __SendDataPart') if isinstance(data, str): #TODO add handling for unicode. connection.send(data) return elif ElementTree.iselement(data): connection.send(ElementTree.tostring(data)) return # Check to see if data is a file-like object that has a read method. elif hasattr(data, 'read'): # Read the file and send it a chunk at a time. while 1: binarydata = data.read(100000) if binarydata == '': break connection.send(binarydata) return else: # The data object was not a file. # Try to convert to a string and send the data. connection.send(str(data)) return
def CalculateDataLength(data): """Attempts to determine the length of the data to send. This method will respond with a length only if the data is a string or and ElementTree element. Args: data: object If this is not a string or ElementTree element this funtion will return None. """ if isinstance(data, str): return len(data) elif isinstance(data, list): return None elif ElementTree.iselement(data): return len(ElementTree.tostring(data)) elif hasattr(data, 'read'): # If this is a file-like object, don't try to guess the length. return None else: return len(str(data))
def save_bridge_api_url(self, bridge_api_url): with open(CONFIG_FILE, 'r') as conf_file: XML_conf_data = conf_file.read().replace('\n', '') root = ET.fromstring(XML_conf_data) client = root.find('client') b_api_url = client.find('bridge_api_url') b_api_url.set('url', str(bridge_api_url)) #print ET.tostring(root) tree = ET.ElementTree(root) tree.write(CONFIG_FILE) #soup = Soup(XML_conf_data) #bridge_api_url_tag = soup.configuration.client.bridge_api_url #bridge_api_url_tag['url'] = str(bridge_api_url) return True
def Save(self, all_in_one=False): """ ??????XML ?? """ #if all_in_one != False: # self.name = filename #print xmllib.tostring(self.root, 'utf-8') print "Call Save" flist=[] for ns in self.xdict: if self.xdict[ns] != None: doc = minidom.parseString( xmllib.tostring(self.xdict[ns], 'utf-8') ) fname = "%s.xml" % ns #print fname x = doc.toprettyxml(encoding="utf-8") f = open(fname, "w") f.write(x) #f.write(xmllib.tostring(g.root, 'utf-8')) f.close() flist.append(os.path.abspath(fname)) return flist
def SaveDataStruct(): print "Call SaveDataStruct" files = generator.Save() #print files Init(); # for k in nslist: # nsvalue = nslist[k] # root = nsvalue[2] # if root == None: # continue # name = "%s.xml" % nsvalue[1] # name = os.path.abspath(name) # print "save ", name # doc = minidom.parseString( xmllib.tostring(root) ) # x = doc.toprettyxml(encoding="utf-8") # f = open(name, "w") # f.write(x) # f.close() # files.append(name) return files
def SaveInAll(self): name = os.path.join(self.folder, u"%s.xml" % autotools.l_ns_name) if self.outfiles.count(name) >0 : return root = None nsnode = None for ns in self.elements: if root == None: root = self.elements[ns] nsnode = root.findall("./Namespace")[0] else: for inode in self.elements[ns].findall("./Namespace"): for tnode in inode.findall("./Type"): nsnode.append(tnode) if root == None: return doc = minidom.parseString( xmllib.tostring(root, 'utf-8') ) x = doc.toprettyxml(encoding="utf-8") self.SaveFile(x, name)
def CreateEnumDataItem(self, node, data): """ ?????? """ ed_ns = data.item_ns ctx = data.item_val ed_type, ed_desc, ed_items = ctx[:3] ed_id = "%s.%s" %(ed_ns, ed_type) tnode = xmllib.Element("Type", {"Id": ed_id,"Name":ed_type, "Uuid": self.GetTypeUuid(ed_type, ed_ns), "xsi:type":"Types:Enumeration" } ) xmllib.SubElement(tnode, "Description").text = ed_desc #xmllib.SubElement(tnode, "Source").text = "%s[%s]" %(data.source, data.part_name) for item in ed_items: it_name, it_value, it_desc = item[:3] it_id = "%s.%s" %(ed_id, it_name) inode = xmllib.SubElement(tnode, "Literal", {"Id":it_id,"Name":it_name, "Value":str(int( it_value ) ) }) xmllib.SubElement(inode, "Description").text = it_desc node.append(tnode) #cache type node self.datastructs[ed_id] = xmllib.tostring(tnode)
def volumeInfo(volumeName=None, remoteServer=None): """ Returns: {VOLUMENAME: {'brickCount': BRICKCOUNT, 'bricks': [BRICK1, BRICK2, ...], 'options': {OPTION: VALUE, ...}, 'transportType': [TCP,RDMA, ...], 'uuid': UUID, 'volumeName': NAME, 'volumeStatus': STATUS, 'volumeType': TYPE, 'disperseCount': DISPERSE_COUNT, 'redundancyCount': REDUNDANCY_COUNT}, ...} """ command = _getGlusterVolCmd() + ["info"] if remoteServer: command += ['--remote-host=%s' % remoteServer] if volumeName: command.append(volumeName) xmltree = _execGlusterXml(command) try: return _parseVolumeInfo(xmltree) except _etreeExceptions: raise GlusterCmdFailedException(err=[etree.tostring(xmltree)])
def volumeGeoRepStatus(volumeName, remoteServer=None): """ Arguments: * VolumeName Returns: {VOLUMENAME: {'slaves': [{SLAVENAME:{ 'nodecount': COUNT, 'faulty': COUNT, 'notstarted': COUNT, 'stopped': COUNT, 'passive':COUNT, 'detail': detailed message, 'status': GEOREPSTATUS, 'name': SLAVESESSIONNAME}} ]} """ command = _getGlusterVolCmd() + ["geo-replication", volumeName, "status"] if remoteServer: command += ['--remote-host=%s' % remoteServer] xmltree = _execGlusterXml(command) try: return _parseVolumeGeoRepStatus(volumeName, xmltree) except _etreeExceptions: raise GlusterCmdFailedException(err=[etree.tostring(xmltree)])
def peerStatus(): """ Returns: [{'hostname': HOSTNAME, 'uuid': UUID, 'status': STATE}, ...] Note: Current host will be the first entry in the list with name as 'localhost' and status as CONNECTED """ command = _getGlusterPeerCmd() + ["status"] xmltree = _execGlusterXml(command) try: return _parsePeerStatus(xmltree, "localhost", hostUUIDGet(), HostStatus.CONNECTED) except _etreeExceptions: raise GlusterCmdFailedException(err=[etree.tostring(xmltree)])
def create_xml(self): for i in range(self._hyperparams['num_objects']): xmldir = '/'.join(str.split(self._hyperparams['filename'], '/')[:-1]) mass = np.random.uniform(.01, 1.) root = ET.Element("top") ET.SubElement(root, "inertial", pos="0 0 0", mass="{}".format(mass), diaginertia="{0} {1} {2}".format(mass/2., mass/2., mass/2.)) tree = ET.ElementTree(root) xml_str = minidom.parseString(ET.tostring( tree.getroot(), 'utf-8')).toprettyxml(indent=" ") xml_str = xml_str.splitlines()[1:] xml_str = "\n".join(xml_str) with open(xmldir+"/mass{}.xml".format(i), "wb") as f: f.write(xml_str)
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'entry' rootClass = entry rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def test_matrix(self): table = eTree.SubElement(self.row, 'mtable') tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'a' td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'b' tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'c' td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'd' self.assertEqual(eTree.tostring(self.math), converter.convert(r'\begin{matrix}a & b \\ c & d \end{matrix}'))
def test_matrix_without_begin_and_end(self): # taken from MathJax table = eTree.SubElement(self.row, 'mtable') tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'a' td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'b' tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'c' td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'd' self.assertEqual(eTree.tostring(self.math), converter.convert(r'\matrix{a & b \\ c & d}'))
def test_matrix_with_negative_sign(self): table = eTree.SubElement(self.row, 'mtable') tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd') mo = eTree.SubElement(td, 'mo') mo.text = '−' mi = eTree.SubElement(td, 'mi') mi.text = 'a' td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'b' tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'c' td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'd' self.assertEqual(eTree.tostring(self.math), converter.convert(r'\begin{matrix}-a & b \\ c & d \end{matrix}'))
def test_pmatrix(self): mo = eTree.SubElement(self.row, 'mo') mo.text = '(' table = eTree.SubElement(self.row, 'mtable') tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'a' td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'b' tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'c' td = eTree.SubElement(tr, 'mtd') mi = eTree.SubElement(td, 'mi') mi.text = 'd' mo = eTree.SubElement(self.row, 'mo') mo.text = ')' self.assertEqual(eTree.tostring(self.math), converter.convert(r'\begin{pmatrix}a & b \\ c & d \end{pmatrix}'))
def test_simple_array(self): table = eTree.SubElement(self.row, 'mtable') tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd', columnalign='center') mn = eTree.SubElement(td, 'mn') mn.text = '1' td = eTree.SubElement(tr, 'mtd', columnalign='right') mn = eTree.SubElement(td, 'mn') mn.text = '2' tr = eTree.SubElement(table, 'mtr') td = eTree.SubElement(tr, 'mtd', columnalign='center') mn = eTree.SubElement(td, 'mn') mn.text = '3' td = eTree.SubElement(tr, 'mtd', columnalign='right') mn = eTree.SubElement(td, 'mn') mn.text = '4' self.assertEqual(eTree.tostring(self.math), converter.convert(r'\begin{array}{cr} 1 & 2 \\ 3 & 4 \end{array}'''))
def parseEquation(eqnElement, varToUnit): if eqnElement[0].tag != "eq": print ET.tostring(eqnElement) assert(eqnElement[0].tag == "eq") lhsElement = eqnElement[1] rhsElement = eqnElement[2] isDiff = 0 if lhsElement.tag == "ci": lhs = lhsElement.text.strip() else: assert(lhsElement.tag == "apply") assert(lhsElement.find("diff") != None) assert(lhsElement.find("bvar/ci") != None) assert(lhsElement.find("ci") != None) lhs = lhsElement.find("ci").text.strip() isDiff=1 (rhs, depend) = parseRhs(rhsElement) unit = varToUnit[lhs] return Equation(lhs, rhs, unit, depend, isDiff)
def _do_scheme(self): scheme = Scheme(self.title) scheme.description = self.description scheme.use_external_validation = self.use_external_validation scheme.streaming_mode = Scheme.streaming_mode_xml scheme.use_single_instance = self.use_single_instance for argument in self.extra_arguments(): name = argument['name'] title = argument.get('title', None) description = argument.get('description', None) validation = argument.get('validation', None) data_type = argument.get('data_type', Argument.data_type_string) required_on_edit = argument.get('required_on_edit', False) required_on_create = argument.get('required_on_create', False) scheme.add_argument( Argument(name, title=title, description=description, validation=validation, data_type=data_type, required_on_edit=required_on_edit, required_on_create=required_on_create)) return ET.tostring(scheme.to_xml())
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'QueryResultType' rootClass = QueryResultType rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'OrganizationReferenceType' rootClass = OrganizationReferenceType rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'TaskType' rootClass = TaskType rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'NetworkType' rootClass = NetworkType rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'SessionType' rootClass = SessionType rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'OrgListType' rootClass = OrgListType rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'OrgType' rootClass = OrgType rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def parseEtree(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'ResourceEntitiesType' rootClass = ResourceEntitiesType rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping
def getLatestStat(root, interval=1): try: el = root.findall('host/statistics/timestamp')[-1] except (_etreeExceptions + (IndexError,)): raise SadfXmlErrorException(err=[etree.tostring(root)]) d = utils.xml2dict(el) statTime = datetime.strptime("%s %s" % (d['timestamp']['date'], d['timestamp']['time']), "%Y-%m-%d %H:%M:%S") minutes = timedelta(minutes=interval) now = utcnow() if (now - statTime) <= minutes: return d['timestamp'] else: return None
def update(self, item_id, entry, action="update"): tree = ET.Element('entry') for key, val in entry.items(): ET.SubElement(tree, key).text = str(val) encoded = ET.tostring(tree).decode('utf-8') xml_item = '<?xml version="1.0" encoding="UTF-8"?>' + encoded payload = {'data': xml_item} r = requests.post( self.base_url + '/animelist/{}/'.format(action) + str(item_id) + '.xml', data=payload, auth=(self.username, self.password), headers={'User-Agent': self.user_agent} ) return r.status_code
def open_soap_envelope(text): """ :param text: SOAP message :return: dictionary with two keys "body"/"header" """ try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc) assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE assert len(envelope) >= 1 content = {"header": [], "body": None} for part in envelope: if part.tag == '{%s}Body' % soapenv.NAMESPACE: assert len(part) == 1 content["body"] = ElementTree.tostring(part[0], encoding="UTF-8") elif part.tag == "{%s}Header" % soapenv.NAMESPACE: for item in part: _str = ElementTree.tostring(item, encoding="UTF-8") content["header"].append(_str) return content
def get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion( self, assertion_tag, advice_tag): for tmp_encrypted_assertion in \ self.assertion.advice.encrypted_assertion: if tmp_encrypted_assertion.encrypted_data is None: prefix_map = self.get_prefix_map([ tmp_encrypted_assertion._to_element_tree().find( assertion_tag)]) tree = self._to_element_tree() encs = tree.find(assertion_tag).find(advice_tag).findall( tmp_encrypted_assertion._to_element_tree().tag) for enc in encs: assertion = enc.find(assertion_tag) if assertion is not None: self.set_prefixes(assertion, prefix_map) return ElementTree.tostring(tree, encoding="UTF-8").decode('utf-8')
def toString(root): data = """<?xml version="1.0" encoding="utf-8"?>\n""" INDENT = 2 # Generate indentation def _indentNode(node, level=0): if node.text is not None and node.text.strip(): return elif len(node.getchildren()): indent = "\n" + " " * (level + 1) * INDENT node.text = indent for child in node.getchildren(): child.tail = indent _indentNode(child, level + 1) if len(node.getchildren()): node.getchildren()[-1].tail = "\n" + " " * level * INDENT _indentNode(root, 0) data += XML.tostring(root) + "\n" return data
def writeXML(self, etree): path = config.pushservice.xmlpath.value indent(etree) data = tostring(etree, 'utf-8') f = None try: f = open(path, 'w') if data: f.writelines(data) except Exception, e: print _("PushService Exception in writeXML: ") + str(e) finally: if f is not None: f.close() # Save time and cache file content self.mtime = os.path.getmtime( path ) self.cache = etree
def send_feedback(self): """Print stored items to console/Alfred as XML.""" root = ET.Element('items') for item in self._items: root.append(item.elem) sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n') sys.stdout.write(ET.tostring(root).encode('utf-8')) sys.stdout.flush() #################################################################### # Updating methods ####################################################################
def write_to(self, stream): """Write an XML representation of self, an ``Event`` object, to the given stream. The ``Event`` object will only be written if its data field is defined, otherwise a ``ValueError`` is raised. :param stream: stream to write XML to. """ if self.data is None: raise ValueError("Events must have at least the data field set to be written to XML.") event = ET.Element("event") if self.stanza is not None: event.set("stanza", self.stanza) event.set("unbroken", str(int(self.unbroken))) # if a time isn't set, let Splunk guess by not creating a <time> element if self.time is not None: ET.SubElement(event, "time").text = str(self.time) # add all other subelements to this Event, represented by (tag, text) subelements = [ ("source", self.source), ("sourcetype", self.sourceType), ("index", self.index), ("host", self.host), ("data", self.data) ] for node, value in subelements: if value is not None: ET.SubElement(event, node).text = value if self.done: ET.SubElement(event, "done") stream.write(ET.tostring(event)) stream.flush()
def __str__(self): return cElementTree.tostring(self.__content)
def get_mixed_text(tree, node): elem = tree.find(node) lines = (elem.text + ''.join(map(ET.tostring, elem))).strip() return lines.strip()
def ToString(self, string_encoding='UTF-8'): """Converts the Atom object to a string containing XML.""" return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding)
def ToString(self): element_tree = self._TransferToElementTree(ElementTree.Element('')) return ElementTree.tostring(element_tree, encoding="UTF-8")