本文整理汇总了Python中xml.etree.ElementTree.SubElement类的典型用法代码示例。如果您正苦于以下问题:Python SubElement类的具体用法?Python SubElement怎么用?Python SubElement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SubElement类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _prepare_xml_request
def _prepare_xml_request(self, module, leads):
root = Element(module)
# Row counter
no = 1
for lead in leads:
row = Element("row", no=str(no))
root.append(row)
assert type(lead) == dict, "Leads must be dictionaries inside a list, got:" + str(type(lead))
for key, value in lead.items():
# <FL val="Lead Source">Web Download</FL>
# <FL val="First Name">contacto 1</FL>
fl = Element("FL", val=key)
if type(value) == dict: # If it's an attached module, accept multiple groups
mod_attach_no = 1
for module_key, module_value in value.items(): # The first group defines the module name, yank that and iterate through the contents
for mod_item in module_value:
mod_fl = SubElement(fl, module_key, no=str(mod_attach_no))
for mod_item_key, mod_item_value in mod_item.items():
attach_fl = SubElement(mod_fl, "FL", val=mod_item_key)
attach_fl.text = mod_item_value
mod_attach_no += 1
elif type(value) not in [str, unicode]:
fl.text = str(value)
else:
fl.text = value
row.append(fl)
no += 1
return root
示例2: _create_update_feed
def _create_update_feed(self, cell_list):
feed = Element('feed', {'xmlns': ATOM_NS,
'xmlns:batch': BATCH_NS,
'xmlns:gs': SPREADSHEET_NS})
id_elem = SubElement(feed, 'id')
id_elem.text = construct_url('cells', self)
for cell in cell_list:
entry = SubElement(feed, 'entry')
SubElement(entry, 'batch:id').text = cell.element.find(_ns('title')).text
SubElement(entry, 'batch:operation', {'type': 'update'})
SubElement(entry, 'id').text = cell.element.find(_ns('id')).text
edit_link = finditem(lambda x: x.get('rel') == 'edit',
cell.element.findall(_ns('link')))
SubElement(entry, 'link', {'rel': 'edit',
'type': edit_link.get('type'),
'href': edit_link.get('href')})
SubElement(entry, 'gs:cell', {'row': str(cell.row),
'col': str(cell.col),
'inputValue': unicode(cell.value)})
return feed
示例3: addDataToForm
def addDataToForm(form, element, subelement):
print form
elem = SubElement(person, element)
for key in form.keys():
for value in form.getlist(key):
subelem = SubElement(elem, subelement)
subelem.text = value
示例4: modify_vrt
def modify_vrt(vrt, scale):
"""
Makes modifications to the vrt file to fix the values.
:param vrt: VRT file to be processed
:param scale: Scale value from get_metadata_item function
:return: None
"""
doc = parse(vrt)
root = doc.getroot()
# Fix the datatype if it is wrong
raster_band = root.find('VRTRasterBand')
raster_band.set('dataType', 'Float32')
# Add the scale to the vrt file
source = root.find('VRTRasterBand').find('ComplexSource')
scale_ratio = SubElement(source, 'ScaleRatio')
scale_ratio.text = scale
# Write the scale input
# vrt files are overwritten with the same name
doc.write(vrt, xml_declaration=True)
示例5: createAndWriteXML
def createAndWriteXML(upload_id, writeToDB):
completeVase = Element('vase')
for i in range(len(finalRight)):
pointpair = SubElement(completeVase, 'pointpair')
left = SubElement(pointpair, 'left')
right = SubElement(pointpair, 'right')
t = SubElement(pointpair, 't')
xRight = SubElement(right, 'x')
xLeft = SubElement(left, 'x')
yRight = SubElement(right, 'y')
yLeft = SubElement(left, 'y')
t.text = "0"
xRight.text = str(finalRight[i][0])
xLeft.text = str(finalLeft[i][0])
yRight.text = str(finalRight[i][1])
yLeft.text = str(finalLeft[i][1])
if writeToDB == 'True':
writeToDB(upload_id, tostring(completeVase))
#print "Content-type: text/html"
#print
print tostring(completeVase)
示例6: compile_while
def compile_while(tree, tok_type, tok):
subR = SubElement(tree, 'whileStatement')
# while
temp = SubElement (subR, tok_type)
temp.text = tok
tok_type, tok = next(token_it)
# '('
temp = SubElement (subR, tok_type)
temp.text = tok
# ( INSIDE )
tok_type, tok = compile_expression(subR)
# ')'
temp = SubElement (subR, tok_type)
temp.text = tok
tok_type, tok = next(token_it)
# '{'
temp = SubElement (subR, tok_type)
temp.text = tok
tok_type, tok = next(token_it)
tok_type, tok = statements(subR, tok_type, tok)
# '}'
temp = SubElement (subR, tok_type)
temp.text = tok
示例7: updateLine
def updateLine(firstrow, method, attr):
root, body = getBaseXML()
action = SubElement(body, 'ns:' + method)
for i in range(len(attr)):
if '-' in firstrow[i]:
# pattern;partition;altnum-nummask;altnum-partition
#<altnum>
# <nummask>XXXX</nummask>
# <partition>CLUSTERDN</partition>
#</altnum>
parentchild = firstrow[i].split('-')
#altnum
parent = parentchild[0]
#nummask
child = parentchild[1]
#<altnum>
l1 = SubElement(action, parent)
#<altnum><nummask>
l2 = SubElement(l1, child)
#<altnum><nummask>XXXX
l2.text = attr[i]
else:
l1 = SubElement(action, firstrow[i])
l1.text = attr[i]
xmldata = ElementTree.tostring(root, encoding='utf-8')
logger.info('Updating Line ' + attr[0])
for i in range(len(firstrow)):
logger.debug(firstrow[i] + ': ' + attr[i])
result = runAxl(method, xmldata)
logger.info(result)
示例8: sendXML
def sendXML(self):
root = self.tree.getroot()
if self.comboBox1.Value in self.runCollection:
bob = self.tree.getiterator("hrun")
for i in bob:
if i.attrib["runName"] == self.comboBox1.Value:
i.find("target").text = self.cTarget.Value
i.find("targid").text = self.cTargID.Value
i.find("targkey").text = self.cTargKey.Value
i.find("targlength").text = self.cTargLength.Value
i.find("buffid").text = self.cBuffID.Value
i.find("buffer").text = self.cBuffer.Value
i.find("buffkey").text = self.cBuffKey.Value
i.find("rootfolder").text = self.cRoot.Value
i.find("waterbody").text = self.cWater.Value
i.find("wabodyid").text = self.cWabodyid.Value
i.find("subsett").text = self.cSubsetT.Value
i.find("subsetc").text = self.cSubsetC.Value
else:
hrun = SubElement(root, "hrun")
hrun.attrib["runName"] = self.comboBox1.Value
SubElement(hrun, "target").text = self.cTarget.Value
SubElement(hrun, "targid").text = self.cTargID.Value
SubElement(hrun, "targkey").text = self.cTargKey.Value
SubElement(hrun, "targlength").text = self.cTargLength.Value
SubElement(hrun, "buffid").text = self.cBuffID.Value
SubElement(hrun, "buffer").text = self.cBuffer.Value
SubElement(hrun, "buffkey").text = self.cBuffKey.Value
SubElement(hrun, "rootfolder").text = self.cRoot.Value
SubElement(hrun, "waterbody").text = self.cWater.Value
SubElement(hrun, "wabodyid").text = self.cWabodyid.Value
SubElement(hrun, "subsett").text = self.cSubsetT.Value
SubElement(hrun, "subsetc").text = self.cSubsetC.Value
ElementTree(root).write(file=os.getcwd() + "\\xmltest.xml")
self.comboRefresh()
示例9: getConfig
def getConfig(self):
"""Generates a configuration file for this projection"""
tree = Element('projection')
SubElement(tree, 'id').text = self.id
SubElement(tree, 'title').text = self.title
SubElement(tree, 'startyear').text = self.getProjection()[0]['year']
SubElement(tree, 'endyear').text = self.getProjection()[-1]['year']
SubElement(tree, 'graph').text = self.absolute_url() + '/getGraph'
SubElement(tree, 'layer').text = self.zone.absolute_url() + \
'/at_download/simImage'
SubElement(tree, 'redevelopment').text = str(self.redevelopment)
e = SubElement(tree, 'pop_density')
if self.pop_density:
e.text = self.pop_density.absolute_url() + '/at_download/simImage'
e = SubElement(tree, 'emp_density')
if self.emp_density:
e.text = self.emp_density.absolute_url() + '/at_download/simImage'
self.REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain')
self.REQUEST.RESPONSE.setHeader('Content-Disposition',
'attachment; filename="%s_demand.xml"' % self.title)
return tostring(tree, encoding='UTF-8')
示例10: _dispatchSoapRequest
def _dispatchSoapRequest(self, request):
try:
try:
envelope = XML(request.soap_data)
body = envelope.find("{http://schemas.xmlsoap.org/soap/envelope/}Body")
# determine UPnP action
action = body.find("{%s}%s" % (request.soap_ns, request.soap_action))
# look up the action in the service
upnp_action = self.service._actions[request.soap_action]
# build a list of the action arguments
in_args = {}
for arg in action:
in_args[arg.tag] = arg.text
# execute the UPnP action
logger.log_debug("executing %s#%s" % (self.service.serviceID, request.soap_action))
out_args = upnp_action(request, self.service, in_args)
# return the action response
env = Element("s:Envelope")
env.attrib['xmlns:s'] = "http://schemas.xmlsoap.org/soap/envelope/"
env.attrib['s:encodingStyle'] = "http://schemas.xmlsoap.org/soap/encoding/"
env.attrib['xmlns:i'] = "http://www.w3.org/1999/XMLSchema-instance"
body = SubElement(env, "s:Body")
resp = SubElement(body, "u:%sResponse" % request.soap_action)
resp.attrib['xmlns:u'] = request.soap_ns
for (name,type,value) in out_args:
arg = SubElement(resp, name)
arg.attrib["i:type"] = type
arg.text = value
output = xmlprint(env)
return HttpResponse(200, headers={'EXT': ''}, stream=output)
except UPNPError, e:
raise e
except Exception, e:
logger.log_error("caught unhandled exception: %s" % e)
raise UPNPError(500, "Internal server error")
示例11: GET
def GET(self, dados):
now = datetime.datetime.now()
weekend = set([6, 7])
retorno = Element('compra')
aprovada = SubElement(retorno , 'aprovada')
mensagem = SubElement(retorno, 'mensagem')
splitados = dados.split('|')
emp = splitados[0]
vlr = float(splitados[1])
qtd = splitados[2]
if float(qtd).__mod__(100) == 0: #and now.hour >= 18:
minimo , maximo = self.verifica_compra(emp)
if vlr > float(minimo) and vlr > float(maximo):
aprovada.text = 'Nao'
mensagem.text = 'Valor Invalido!(Abaixo do minimo ' + str(minimo) + ' ou maior que o maximo ' + str(maximo) + ')'
else:
if now.isoweekday() not in weekend:
aprovada.text = 'Sim'
mensagem.text = 'Compra Aprovada'
else:
aprovada.text = 'Pendente'
mensagem.text = "Pregao Fechado!"
else:
aprovada.text = 'Nao'
mensagem.text = 'Qtd Invalida'
return prettify(retorno);
示例12: create_proppatch
def create_proppatch(setprops, delprops, namespaces=None):
"""Construct and return XML string for PROPPATCH.
setprops -- Mapping with properties to set.
delprops -- Iterable with element names to remove.
namespaces -- Mapping (prefix->namespace) with additional namespaces,
if necessary.
"""
# RFC 2518, 12.13 propertyupdate XML element
# <!ELEMENT propertyupdate (remove | set)+ >
propertyupdate = Element("propertyupdate", _NS)
if namespaces:
_addnamespaces(propertyupdate, namespaces)
# RFC 2518, 12.13.2 set XML element
# <!ELEMENT set (prop) >
if setprops:
set_ = SubElement(propertyupdate, "set")
prop = SubElement(set_, "prop")
items_iterator = iter(list(setprops.items())) if PYTHON2 else list(setprops.items())
for (propname, propvalue) in items_iterator:
prop = SubElement(prop, propname)
prop.text = propvalue
# RFC 2518, 12.13.1 set XML element
# <!ELEMENT remove (prop) >
if delprops:
remove = SubElement(propertyupdate, "remove")
prop = SubElement(remove, "prop")
for propname in delprops:
prop = SubElement(prop, propname)
return tostring(propertyupdate, "UTF-8")
示例13: __init__
def __init__(self, id, route, chunk):
((rfrom, rdest),) = route
chunk, (cnum, maxc, fname, totalbsize) = chunk
cont = Element('content')
idtag = SubElement(cont, 'id')
idtag.text = id
rattrs = {
'from': rfrom,
'to': rdest,
}
routetag = SubElement(cont, 'route', rattrs)
cattrs = {
'number': cnum,
'maxchunk': maxc,
'filename': fname,
'totalbsize': totalbsize,
}
chunktag = SubElement(cont, 'chunk', cattrs)
chunktag.text = chunk
props = {
'type': 'file_chunk',
}
MMessage.__init__(self, TYPE, cont, props)
示例14: mergePopulationData
def mergePopulationData(populationFile, regionFile, mergedFile):
csvReader = csv.reader(open(populationFile), delimiter=',', quotechar='"')
inhabDict = {}
for entry in csvReader:
if csvReader.line_num <= 3:
continue
while(len(entry[0]) < 2):
entry[0] = '0' + entry[0]
while(len(entry[2]) < 2):
entry[2] = '0' + entry[2]
while(len(entry[3]) < 4):
entry[3] = '0' + entry[3]
while(len(entry[4]) < 3):
entry[4] = '0' + entry[4]
inhabDict["".join(entry[:5])] = str(entry[6]).replace(' ', '')
root = ET.ElementTree(file=regionFile).getroot()
for parents in root.findall("./*"):
for elem in parents.findall("param[7]"):
RSValue = str(elem.attrib)[11:23]
inhabitants = SubElement(parents, 'param')
if RSValue in inhabDict:
inhabitants.clear()
inhabitants.attrib = {
'key': "INHABITANTS", 'value': inhabDict[RSValue]}
outstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ")
with open(mergedFile, 'w') as out:
out.write(outstr.encode('utf-8'))
示例15: story_feed
def story_feed(request, story):
story = Story.objects.get(slug=story)
rss = Element('rss')
rss.set("version","2.0")
channel = SubElement(rss,'channel')
title = SubElement(channel,'title')
title.text = story.title
link = SubElement(channel,'link')
link.text = request.build_absolute_uri(reverse("story"))
desc = SubElement(channel,'description')
desc.text = story.description
chapters = story.chapters.all()
for index in chapters:
item = SubElement(channel,'item')
title_c = SubElement(item,'title')
title_c.text = index.title
link = SubElement(item,'link')
link.text = request.build_absolute_uri(index.get_absolute_url())
return HttpResponse(tostring(rss, encoding='UTF-8'))