本文整理汇总了Python中xml.etree.ElementTree.SubElement类的典型用法代码示例。如果您正苦于以下问题:Python SubElement类的具体用法?Python SubElement怎么用?Python SubElement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SubElement类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:elboby,项目名称:mfabrik.zoho,代码行数:31,代码来源:crm.py
示例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
开发者ID:goldenboy,项目名称:gspread,代码行数:27,代码来源:models.py
示例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
开发者ID:kispuding,项目名称:konkurzapp,代码行数:7,代码来源:app.py
示例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)
开发者ID:OpenGeoscience,项目名称:nex,代码行数:25,代码来源:hdf2tif.py
示例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)
开发者ID:ohaicristina,项目名称:viv-website,代码行数:26,代码来源:VaseCreation.py
示例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
开发者ID:slarrain,项目名称:nand2tetris,代码行数:30,代码来源:tokenizer.py
示例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)
开发者ID:MrCollaborator,项目名称:CiscoUCScripts,代码行数:34,代码来源:updateAttribute_py2.py
示例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()
开发者ID:kpierce8,项目名称:hydrodiff_beta,代码行数:35,代码来源:HydroDiff.py
示例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')
开发者ID:HelenRouty,项目名称:leamluc,代码行数:26,代码来源:projection.py
示例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")
开发者ID:msfrank,项目名称:Higgins,代码行数:35,代码来源:control_resource.py
示例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);
开发者ID:arthureggert,项目名称:faculdade,代码行数:27,代码来源:BuscaDadosPregao.py
示例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")
开发者ID:StickNClutch,项目名称:ownNotes,代码行数:31,代码来源:creator.py
示例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)
开发者ID:btrzcinski,项目名称:netchat,代码行数:27,代码来源:filetransfer.py
示例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'))
开发者ID:702nADOS,项目名称:sumo,代码行数:28,代码来源:evacuation.py
示例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'))
开发者ID:gitter-badger,项目名称:fictionhub,代码行数:28,代码来源:views.py
示例16: egressports_getConfig
def egressports_getConfig(fileName, portList):
global egrPorts
global egrPLst
crossconnects = Element('opsw:cross-connects', {'xmlns:plts':"http://www.polatis.com/yang/polatis-switch",
'xmlns:opsw':"http://www.polatis.com/yang/optical-switch"})
egrSymbol = re.split(r'[\d]', portList)
if str(egrSymbol[1]) == ',' or str(egrSymbol[1]) == '':
egrPLst = portList.split(',')
if str(ingSymbol[2]) == '-' or str(ingSymbol[1]) == '-':
egrPLst = []
egrPLst1 = portList.split('-')
for i in range(int(egrPLst1[0]), int(egrPLst1[1])+1):
egrPLst.append(i)
logger.info('egress port list: %s' % egrPLst)
else:
logger.error('Give for example comma or hypen seperated values ...\n\n')
l = len(egrPLst)
for i in range(0, l):
a = egrPLst[i]
if a in egrPorts:
pairs = SubElement(crossconnects, 'opsw:pairs')
egress = SubElement(pairs, 'opsw:egress')
egress.text = str(a)
else:
pairs = SubElement(crossconnects, 'opsw:pairs')
egress = SubElement(pairs, 'opsw:egress')
egress.text = str(a)
xmlstr = tostring(crossconnects)
getConfig('getConfig - Query given egress ports', xmlstr, fileName)
开发者ID:valarmathip,项目名称:Terafast,代码行数:35,代码来源:crossconnects.py
示例17: topology_list
def topology_list():
logger.info('GET topology list.')
try:
#open DB connection.
tpldb_setup()
#create <topology_list>
xml_topology_list = Element(const.XML_TAG_TOPOL_LIST)
nw_list = Network.query.all()
for nw in nw_list:
#add <topology type='slice' last_update_time='xxx' name='xxx' owner='xxx'>
xml_topology = SubElement(xml_topology_list, const.XML_TAG_TOPOL,
{const.XML_ATTR_TYPE:nw.type,
const.XML_ATTR_LAST_UPD_TIME:str(nw.last_update_time),
const.XML_ATTR_NAME:nw.network_name
})
if nw.type == const.TYPE_NW_SLICE:
xml_topology.set(const.XML_ATTR_OWN,nw.user)
except Exception:
logger.exception('GET topology list error.')
return HTTPResponse("GET topology list error.", status=500)
finally:
#close DB connection.
tpldb_close()
return util.prettify(xml_topology_list)
开发者ID:HalasNet,项目名称:felix,代码行数:30,代码来源:topology_rest.py
示例18: set
def set(self, index, values):
for key, value in values.items():
item = self._root[index].find(key)
if item is None:
item = SubElement(self._root[index], key)
item.text = value
开发者ID:Haehnchen,项目名称:MyTubeExt,代码行数:7,代码来源:MyTubeExtScreens.py
示例19: dict_to_xml
def dict_to_xml(self, root_elm, data):
for key in data.keys():
sub_data = data[key]
elm = SubElement(root_elm, key)
is_list = isinstance(sub_data, list) or isinstance(sub_data, tuple)
is_plural = key[len(key)-1] == "s"
plural_name = key[:len(key)-1]
# Key references a dict. Unroll the dict
# as it's own XML node with subnodes
if isinstance(sub_data, dict):
self.dict_to_xml(elm, sub_data)
# Key references a list/tuple
elif is_list:
# key name is a plural. This means each item
# in the list needs to be wrapped in an XML
# node that is a singular version of the list name.
if is_plural:
for d in sub_data:
plural_name = self.PLURAL_EXCEPTIONS.get(plural_name, plural_name)
self.dict_to_xml(SubElement(elm, plural_name), d)
# key name isn't a plural. Just insert the content
# as an XML node with subnodes
else:
for d in sub_data:
self.dict_to_xml(elm, d)
# Normal element - just inser the data.
else:
elm.text = str(sub_data)
return root_elm
开发者ID:skillflip,项目名称:pyxero,代码行数:35,代码来源:manager.py
示例20: get_database_deployment
def get_database_deployment(dbid, sid=0):
deployment_top = Element('deployment')
deployment = HTTPListener.Global.DEPLOYMENT[dbid]
value = copy.deepcopy(deployment)
db = HTTPListener.Global.DATABASES[dbid]
if not sid == 0:
server = HTTPListener.Global.SERVERS.get(sid)
value = DeploymentConfiguration.get_specific_directories(value, server, dbid)
host_count = len(db['members'])
value['cluster']['hostcount'] = host_count
# Add users
addTop = False
for key, duser in HTTPListener.Global.DEPLOYMENT_USERS.items():
if duser['databaseid'] == dbid:
# Only create subelement if users have anything in this database.
if addTop != True:
users_top = SubElement(deployment_top, 'users')
addTop = True
uelem = SubElement(users_top, "user")
uelem.attrib["name"] = duser["name"]
uelem.attrib["password"] = duser["password"]
uelem.attrib["roles"] = duser["roles"]
plaintext = str(duser["plaintext"])
if isinstance(duser["plaintext"], bool):
if duser["plaintext"] == False:
plaintext = "false"
else:
plaintext = "true"
uelem.attrib["plaintext"] = plaintext
handle_deployment_dict(deployment_top, dbid, value, True)
xmlstr = tostring(deployment_top,encoding='UTF-8')
return xmlstr
开发者ID:aamadeo27,项目名称:voltdb,代码行数:34,代码来源:DeploymentConfig.py
注:本文中的xml.etree.ElementTree.SubElement类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论