本文整理汇总了Python中xml.etree.cElementTree.tostring函数的典型用法代码示例。如果您正苦于以下问题:Python tostring函数的具体用法?Python tostring怎么用?Python tostring使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tostring函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: show_settings
def show_settings(root, path, option_name='--show-settings'):
c = resolve_component_path(root, path.split('/'), option_name)
s = msaview.presets.setting_types[c.msaview_classname].from_value(c, msaview.presets)
e = etree.Element('settings')
s.encode(e)
msaview.preset.indent(e)
print etree.tostring(e)
开发者ID:yohell,项目名称:msaview,代码行数:7,代码来源:__init__.py
示例2: test_merge_1
def test_merge_1(self):
root= et.fromstring(xml_file5)
x= merge(root)
y= et.fromstring(xml_file6)
z=et.tostring(y)
string = et.tostring(x)
self.assert_(string == z)
开发者ID:cs327e,项目名称:cs327e-wcdb3-tests,代码行数:7,代码来源:ajw2232-TestWCDB3.py
示例3: json_to_elem
def json_to_elem(jsonobj):
'''
>>> o = '{"tag1": "1", "tag2": "2"}'
>>> json_to_elem(json.loads(o))
<tag1>1</tag1>
<tag2>2</tag2>
'''
attrs = {}
text = ''
subels = []
for key in jsonobj.keys():
value = jsonobj[key]
if isinstance(value, dict):
for k, v in value.items():
if k[:1] == "@":
attrs[k[1:]] = v
elif k == "#text":
text = v
elif isinstance(value, dict):
tail = v
else:
text = value
e = ET.Element(key, attrs)
e.text = text
#e.tail = tail
print ET.tostring(e)
开发者ID:andrew-malkov,项目名称:Riurik,代码行数:27,代码来源:json2xml.py
示例4: to_xml_stream
def to_xml_stream(self, stream, pretty=True, indent=' ', encoding='UTF-8', **kwargs):
'''Dump object to a file object like stream.'''
close = False
if isinstance(stream, basestring):
close = True
if _xmldomext: stream = file(stream, 'w')
else: stream = codecs.open(stream, mode='w', encoding=encoding, errors='replace')
try:
e = self.to_xml_elt(**kwargs)
if pretty:
if _xmldomext:
PrettyPrint(Sax2.Reader().fromString(ElementTree.tostring(e)),
stream=stream, encoding=encoding, indent=indent, preserveElements=None)
else:
# minidom.parseString(
# ElementTree.tostring(e)).writexml(
# stream, addindent=indent, newl='\n')
pretty_indent(e)
stream.write(ElementTree.tostring(e))
else:
d = ElementTree.ElementTree(e)
#d.write(stream, xml_declaration=True, method="xml")
d.write(stream, encoding=encoding, xml_declaration=True, method="xml")
finally:
if close: stream.close()
return e
开发者ID:VACUMM,项目名称:vacumm,代码行数:26,代码来源:xml.py
示例5: Serialize
def Serialize(root, uri_prefixes=None, pretty_print=True):
"""Serializes XML to a string."""
root_copy = ElementTree.fromstring(ElementTree.tostring(root))
SetPrefixes(root_copy, uri_prefixes or {})
if pretty_print:
Indent(root_copy)
return ElementTree.tostring(root_copy)
开发者ID:Zippelmitz,项目名称:googlecrisismap,代码行数:7,代码来源:xml_utils.py
示例6: xml_rawquery
def xml_rawquery(self, xml_str, dump_xml=None):
"""
Accepts xmlQuery String and returns XML response String. No object manipulation is done in this method.
"""
if dump_xml == None:
dump_xml = self.__dump_xml
uri = self.uri() + '/nuova'
if dump_xml in ImcUtils.AFFIRMATIVE_LIST:
print '%s ====> %s' % (self.__imc, xml_str)
xml_doc = ET.fromstring(xml_str)
if self.__nossl:
req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
opener = urllib2.build_opener(ImcUtils.SmartRedirectHandler())
resp = opener.open(req)
if type(resp) is list:
if len(resp) == 2 and (resp[0] == 302 or resp[0] == 301):
uri = resp[1]
req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
resp = urllib2.urlopen(req)
#print "status code is:",f[0]
#print "location is:", f[1]
else:
req = urllib2.Request(url=uri, data=ET.tostring(xml_doc))
resp = urllib2.urlopen(req)
rsp = resp.read()
if dump_xml in ImcUtils.AFFIRMATIVE_LIST:
print '%s <==== %s' % (self.__imc, rsp)
return rsp
开发者ID:bdemers,项目名称:ImcSdk,代码行数:34,代码来源:ImcHandle.py
示例7: write_xml
def write_xml(tree,filename=None) :
if filename :
f = file(filename,"w")
f.write(ET.tostring(tree))
f.close()
else :
print ET.tostring(tree)
开发者ID:neumark,项目名称:geopez,代码行数:7,代码来源:process_xml.py
示例8: get_info
def get_info(self, request):
path = self.translate_path(request.form['path'])
parts = path.partition('/representations')
ip = parts[0]
hrefs = self._get_href_variations(parts[1] + parts[2])
namespace = '{http://ead3.archivists.org/schema/}'
tree = ET.parse('%s/metadata/descriptive/EAD.xml' % ip)
# regular file - daoset
for href in hrefs:
did_list = tree.findall(".//%sdid/*/%sdao[@href='%s']/../.."
% (namespace, namespace, href))
if did_list:
o = xmltodict.parse(ET.tostring(did_list[0]))
return json.dumps(o)
# regular file - no daoset
for href in hrefs:
did_list = tree.findall(".//%sdid/%sdao[@href='%s']/.."
% (namespace, namespace, href))
if did_list:
o = xmltodict.parse(ET.tostring(did_list[0]))
return json.dumps(o)
# directory
for href in hrefs:
did_list = tree.findall(".//%sc[@base='%s']/%sdid"
% (namespace, href, namespace))
if did_list:
o = xmltodict.parse(ET.tostring(did_list[0]))
return json.dumps(o)
# fallback
return flask.jsonify(
error=404,
error_text='Not Found',
info='No metadata associated to this element'
)
开发者ID:magenta-aps,项目名称:eark-python-bridge,代码行数:34,代码来源:handlers.py
示例9: __init__
def __init__(self, inst_el):
"""
inst_el is an ElementTree element representing a movie instance, extracted from
train.xml or testcases.xml
"""
self.id = inst_el.attrib['id']
for child_el in inst_el:
try:
if child_el.tag == "regy": # opening week revenue
self.target = float(child_el.attrib['yvalue'])
elif child_el.tag == "text": # reviews
self.__dict__[child_el.attrib['tlabel']] = asciify(child_el.text)
elif child_el.tag.endswith('release'): # special weekend releases
self.__dict__[child_el.tag] = False if child_el.text.strip() == "false" else True
elif child_el.tag in self.implicit_list_atts: # these can appear multiple times w/ different vals
if hasattr(self, child_el.tag):
self.__dict__[child_el.tag].append(asciify(child_el.text))
else:
self.__dict__[child_el.tag] = [asciify(child_el.text)]
elif len(child_el) > 0: # list (e.g., actors, genres)
self.__dict__[child_el.tag] = [asciify(el.text) if el.text is not None else "" for el in child_el]
elif len(child_el.attrib) == 0 and child_el.text is None: # just a predicate
self.__dict__[child_el.tag] = True
elif len(child_el.attrib) == 0 and (child_el.tag.startswith('num') or child_el.tag in self.numeric_fields):
self.__dict__[child_el.tag] = float(child_el.text.replace(",","").replace("$",""))
elif len(child_el.attrib) == 0:
self.__dict__[child_el.tag] = asciify(child_el.text)
except Exception:
print ET.tostring(child_el)
import sys
sys.exit(1)
开发者ID:ZXspectrumZ80,项目名称:cs181-spring2014,代码行数:31,代码来源:util.py
示例10: feedback
def feedback(items):
feedback = ET.Element("items")
def processItem(item):
itemToAdd = ET.SubElement(feedback, "item")
data = item.get()
for (k, v) in data["attrib"].iteritems():
if v is None:
continue
itemToAdd.set(k, v)
for (k, v) in data["content"].iteritems():
if v is None:
continue
if k != "fileIcon" and k != "fileType":
child = ET.SubElement(itemToAdd, k)
child.text = v
if k == "icon":
if "fileIcon" in data["content"].keys():
if data["content"]["fileIcon"] == True:
child.set("type", "fileicon")
if "fileType" in data["content"].keys():
if data["content"]["fileType"] == True:
child.set("type", "filetype")
if isinstance(items, list):
for anItem in items:
processItem(anItem)
else:
processItem(items)
print ET.tostring(feedback, encoding="utf-8")
开发者ID:knutwalker,项目名称:tower-alfred-workflow,代码行数:34,代码来源:item.py
示例11: verify
def verify(self, manager, uri, response, respdata, args): #@UnusedVariable
# Get arguments
files = args.get("filepath", [])
# 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"
# look for one file
if len(files) != 1:
return False, " No file to compare response to"
# read in all data from specified file
fd = open(files[0], "r")
try:
try:
data = fd.read()
finally:
fd.close()
except:
data = None
if data is None:
return False, " Could not read data file"
data = manager.server_info.subs(data)
result = True
if data != respdata:
data = data.replace("\n", "\r\n")
if data != respdata:
# If we have an iCalendar file, then unwrap data and do compare
if files[0].endswith(".ics"):
data = data.replace("\r\n ", "")
respdata = respdata.replace("\r\n ", "")
if data != respdata:
result = False
elif files[0].endswith(".xml"):
try:
respdata = tostring(ElementTree(file=StringIO(respdata)).getroot())
except Exception:
return False, " Could not parse XML response: %s" % (respdata,)
try:
data = tostring(ElementTree(file=StringIO(data)).getroot())
except Exception:
return False, " Could not parse XML data: %s" % (data,)
if data != respdata:
result = False
else:
result = False
if result:
return True, ""
else:
error_diff = "\n".join([line for line in unified_diff(data.split("\n"), respdata.split("\n"))])
return False, " Response data does not exactly match file data %s" % (error_diff,)
开发者ID:agx,项目名称:caldav-tester-packaging,代码行数:60,代码来源:dataMatch.py
示例12: check_text_values
def check_text_values(filename, cases_to_check=['addr:city', 'addr:housename', 'addr:street']):
categories = {
'all_capital': re.compile(r'^([A-Z]| )+$'),
'all_small': re.compile(r'^([a-z]| )+$'),
'unicode_text': re.compile(r'[0-9]+'),
'other': re.compile(r'\S')
}
keys = categories.keys()
categories_set = {j: {k: set() for k in keys} for j in cases_to_check}
for event, elem in ET.iterparse(filename):
if elem.tag in ['node', 'way']:
for tag in elem.findall('tag'):
k = tag.attrib['k']
v = tag.attrib['v']
if k == 'addr:housename' and v == u'Calle Santa Mar\xeda n\xba8, 48005 Bilbao':
print ET.tostring(elem)
if k in cases_to_check:
if categories['all_capital'].search(v):
categories_set[k]['all_capital'].add(v)
elif categories['all_small'].search(v):
categories_set[k]['all_small'].add(v)
elif categories['unicode_text'].search(v) is None:
categories_set[k]['unicode_text'].add(v)
else:
categories_set[k]['other'].add(v)
pprint.pprint(categories_set)
开发者ID:dsaiztc,项目名称:OSMDataWrangling,代码行数:31,代码来源:audit_values_basic.py
示例13: retornaPlantilla
def retornaPlantilla(nombreDirectorioPlantillas,xmlEntradaObject,cantidadAlternativas, tipoPregunta, **kwuargs): #,xmlEntradaObject):
#tipoPregunta=nombres.nombreScript(__file__)
contador=0
banderaEstado=False
if 'directorioSalida' in kwuargs.keys():
banderaEstado=True #Indica si se debe imprimir o no el estado de la cantidad de salidas
for plantilla in recogePlantillas(nombreDirectorioPlantillas,tipoPregunta):
plantillaSalida=xmlSalida.plantillaGenericaSalida()
for subRaizSalida in plantillaSalida.iter():
if subRaizSalida.tag=='plantilla':
subRaizSalida.set('tipo',xmlEntradaObject.tipo)
subRaizSalida.set('id',xmlEntradaObject.id)
subRaizSalida.set('idOrigenEntrada',xmlEntradaObject.idOrigenEntrada)
if subRaizSalida.tag=='enunciado':
subRaizSalida.text=plantilla.enunciado.replace('@termino',xmlEntradaObject.termino)
if subRaizSalida.tag=='opciones':
for conjuntoAlternativas in xmlEntradaObject.agrupamientoAlternativas2(cantidadAlternativas):
contador+=1
identificadorItem,identificadorAlternativas=xmlSalida.incrustaAlternativasXml(subRaizSalida, conjuntoAlternativas)
if banderaEstado==True:
xmlSalida.escribePlantilla(kwuargs['directorioSalida'],xmlEntradaObject.tipo, identificadorItem+' '+identificadorAlternativas+' '+str(contador), plantillaSalida,'xml')
else:
print ET.tostring(plantillaSalida, 'utf-8', method="xml")
if banderaEstado==True:
print str(contador)+' Creados'
pass
开发者ID:marcialhernandez,项目名称:Proyecto-titulacion,代码行数:26,代码来源:MC_def_simple.py
示例14: searchAllServers
def searchAllServers(self, query):
xml_combined = None
for server in self.servers:
root = ET.fromstring(server.getSearchXML(query))
data = ET.ElementTree(root).getchildren()
for cont in data.iter('MediaContainer'):
if xml_combined is None:
xml_combined = data
#insertion_point = xml_combined.findall("./MediaContainer")[0]
insertion_point = data
else:
insertion_point.append(cont)
for server in self.sharedServers:
data = ET.ElementTree(ET.fromstring(server.getSearchXML(query)))
for cont in data.iter('MediaContainer'):
if xml_combined is None:
xml_combined = data
#insertion_point = xml_combined.findall("./MediaContainer")[0]
insertion_point = data
else:
insertion_point.append(cont)
dprint(__name__, 0, "test: {0}", ET.tostring(xml_combined))
return ET.tostring(xml_combined)
开发者ID:nrgaway,项目名称:PlexConnect,代码行数:27,代码来源:PlexMgr.py
示例15: main
def main():
"""
:return:
"""
with open("input_data.txt") as f:
i = 0
statements = []
statement = ET.Element("program")
statements.append(statement)
ET.SubElement(statement, "result").text = "a"
for line in f:
statement_components = (line.strip()).split(" ")
statement = ET.Element(statement_components.pop())
statements.append(statement)
i += 1
statement_components.pop()
elements = len(statement_components)
if elements == 1: # a simple assignment
statement.text = statement_components.pop()
elif elements == 2: # unary operation and assignment
operand = statement_components.pop()
operator = ET.SubElement(statement, operators[statement_components.pop()])
operator.text = operand
elif elements == 3: # binary operation and assignment
operand = statement_components.pop()
operator = ET.SubElement(statement, operators[statement_components.pop()])
operator.text = "(" + statement_components.pop() + ", " + operand + ")"
print ET.tostring(statements[i])
开发者ID:pawingard,项目名称:AdventofCode-2015,代码行数:31,代码来源:AofCode_07.py
示例16: _to_rspec
def _to_rspec(self, slice):
"""
See L{GENIAggregate._to_rspec}.
"""
# get all the reserved nodes
reserved = PlanetLabNode.objects.filter(
aggregate__pk=self.pk, slice_set=slice)
# Get the ids of all reserved nodes
node_ids = reserved.values_list("node_id", flat=True)
rspec = "%s" % self.rspec
# parse the rspec
root = et.fromstring(rspec)
# get a mapping from node id to node elem (since this version of
# elementtree doesn't have XPath working well.
node_elems = root.findall(".//node")
node_dict = {}
for node_elem in node_elems:
id = node_elem.get("id", None)
if id:
node_dict[id] = node_elem
# for each node_id in the reservation, find the corresponding
# node_elem and add a sliver tag.
for node_id in node_ids:
node_elem = node_dict[node_id]
et.SubElement(node_elem, "sliver")
logger.debug("Sending PlanetLab Reservation RSpec:\n%s"
% et.tostring(root))
return et.tostring(root)
开发者ID:CarolinaFernandez,项目名称:ocf-expedient-ro,代码行数:35,代码来源:models.py
示例17: et_to_string
def et_to_string(element):
xml = '<?xml version="1.0" ?>'
try:
xml += ET.tostring(element, encoding="unicode")
except LookupError:
xml += ET.tostring(element)
return xml
开发者ID:dls-controls,项目名称:pymalcolm,代码行数:7,代码来源:compat.py
示例18: open_soap_envelope
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
开发者ID:Amli,项目名称:pysaml2,代码行数:25,代码来源:soap.py
示例19: addtorow
def addtorow(self, xpath, data, elem=None):
fullp='/'.join(xpath)
path=None
if elem!=None:
s=self.schemagetall
if fullp in s:
path=fullp
else:
shortp=pathwithoutns(xpath)
if shortp in s:
path=shortp
if path == None:
return
try:
data = cleansubtree.match(etree.tostring(elem)).groups()[0]
except AttributeError:
data = etree.tostring(elem)
else:
s=self.schema
if fullp in s:
path=fullp
else:
shortp=pathwithoutns(xpath)
if shortp in s:
path=shortp
if path==None:
if self.strict==2 and elem==None:
path=xpath
self.resetrow()
msg='Undeclared path in XML-prototype was found in the input data. The path is:\n'
shortp='/'+pathwithoutns(path)
fullp='/'+'/'.join(path)
if shortp!=fullp:
msg+=shortp+'\n'
msg+=fullp+'\nThe data to insert into path was:\n'+functions.mstr(data)
raise etree.ParseError(msg)
else:
if self.row[s[path][0]]=='':
self.row[s[path][0]]=data.replace('\t', self.tabreplace)
return
i=1
attribnum=path+'1'
oldattribnum=path
while attribnum in s:
if self.row[s[attribnum][0]]=='':
self.row[s[attribnum][0]]=data.replace('\t', self.tabreplace)
return
i+=1
oldattribnum=attribnum
attribnum=path+str(i)
self.row[s[oldattribnum][0]]+='\t'+data.replace('\t', self.tabreplace)
开发者ID:KonstantinaGalouni,项目名称:Design-and-Applications-of-Databases,代码行数:59,代码来源:xmlparse.py
示例20: __CoreErrorList
def __CoreErrorList(self):
'''return a list of error strings'''
s = []
if not self.PipelineNode is None:
s.append("Pipeline Element: " + ElementTree.tostring(self.PipelineNode, encoding='utf-8') + '\n')
if not self.VolumeElem is None:
s.append("Volume Element: " + ElementTree.tostring(self.VolumeElem, encoding='utf-8') + '\n');
return s
开发者ID:jamesra,项目名称:nornir-buildmanager,代码行数:8,代码来源:pipelinemanager.py
注:本文中的xml.etree.cElementTree.tostring函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论