本文整理汇总了Python中xml.etree.ElementTree.SubElement.text方法的典型用法代码示例。如果您正苦于以下问题:Python SubElement.text方法的具体用法?Python SubElement.text怎么用?Python SubElement.text使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree.SubElement
的用法示例。
在下文中一共展示了SubElement.text方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: items_xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def items_xml():
"""Returns all the items as an XML file.
Research for this function came from:
https://pymotw.com/2/xml/etree/ElementTree/create.html
"""
session = connect_to_database()
categories = session.query(Category).all()
root = Element('catalog')
for category in categories:
cat_tag = SubElement(root,
'category',
{'id':str(category.id), 'name':category.name})
items = session.query(Item).filter_by(category=category).all()
for item in items:
item_tag = SubElement(cat_tag, 'item', {'id':str(item.id)})
name_tag = SubElement(item_tag, 'name')
name_tag.text = item.name
desc_tag = SubElement(item_tag, 'description')
desc_tag.text = item.description
desc_tag = SubElement(item_tag, 'quantity')
desc_tag.text = str(item.quantity)
session.close()
# Return the XML with a 2 space indent to make it more human readable.
return parseString(tostring(root, 'utf-8')).toprettyxml(indent=' ')
示例2: MDK4AddGroup
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def MDK4AddGroup(ProjectFiles, parent, name, files, project_path):
group = SubElement(parent, 'Group')
group_name = SubElement(group, 'GroupName')
group_name.text = name
for f in files:
fn = f.rfile()
name = fn.name
path = os.path.dirname(fn.abspath)
basename = os.path.basename(path)
path = _make_path_relative(project_path, path)
path = os.path.join(path, name)
files = SubElement(group, 'Files')
file = SubElement(files, 'File')
file_name = SubElement(file, 'FileName')
name = os.path.basename(path)
if ProjectFiles.count(name):
name = basename + '_' + name
ProjectFiles.append(name)
file_name.text = name.decode(fs_encoding)
file_type = SubElement(file, 'FileType')
file_type.text = '%d' % _get_filetype(name)
file_path = SubElement(file, 'FilePath')
file_path.text = path.decode(fs_encoding)
示例3: brandsCatalogXML
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def brandsCatalogXML(brand_id):
if 'username' not in login_session:
response = make_response(json.dumps("You are not authorized, Login is required"), 401)
response.headers['Content-Type'] = 'application/json'
return response
else:
brand = session.query(Brand).filter_by(id=brand_id).one()
items = session.query(Item).filter_by(brand_id=brand_id).all()
root = Element('html')
for i in items:
body = SubElement(root, 'body')
ID = SubElement(body, 'ID')
ID.text = str(i.id)
name = SubElement(body, 'name')
name.text = i.name
price = SubElement(body, 'price')
price.text = i.price
description = SubElement(body, 'description')
description.text = i.description
image = SubElement(body, 'image')
image.text = i.image
print tostring(root)
return app.response_class(tostring(root), mimetype='application/xml')
示例4: updateLine
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
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)
示例5: generateXML
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def generateXML(self, os):
# Structure of document is:
#
# <CALDAV:mkcalendar>
# <DAV:prop>
# <<each property as elements>>
# </DAV:prop>
# </CALDAV:mkcalendar>
# <CALDAV:mkcalendar> element
mkcalendar = Element(caldavxml.mkcalendar)
# <DAV:prop> element
prop = SubElement(mkcalendar, davxml.prop)
# <DAV:displayname> element
if self.displayname:
displayname = SubElement(prop, davxml.displayname)
displayname.text = self.displayname
# <CalDAV:calendar-description> element
if self.description:
description = SubElement(prop, caldavxml.calendar_description)
description.text = self.description
# <CalDAV:timezone> element
if self.timezone:
timezone = SubElement(prop, caldavxml.calendar_timezone)
timezone.text = self.timezone
# Now we have the complete document, so write it out (no indentation)
xmldoc = BetterElementTree(mkcalendar)
xmldoc.writeUTF8(os)
示例6: story_feed
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
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'))
示例7: execute
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def execute(self, mappings, source):
"""Writes the given language code/name mappings to Android XML resource files.
source = string indicating source of the data, for example, 'cldr'
mappings = list of dictionaries containing mappings"""
# In order to be able to to localize a particular, limited set of words across multiple
# languages, here we define a list of language codes to support for every resource file
# generated. Where localized language names are missing, a place holder is printed. If
# ['*'] is specified, then all available language code/name pairs are generated.
COVERAGE_LIST = ['*']
# Get language names in English as a dict for inclusion in XML comments
english_pairs = {}
for entry in mappings:
for k, v in entry.iteritems():
if k == 'en':
english_pairs = v
break
for entry in mappings:
for k, v in entry.iteritems():
dir = os.path.join(os.path.dirname(__file__), self.get_directory(source) +
"../" + source + "-android/values-" + k)
if not os.path.exists(dir):
os.makedirs(dir)
with open(dir + "/arrays.xml", "w") as f:
top = Element('resources')
if k in english_pairs.keys():
top_comment = ElementTree.Comment(' ' + english_pairs[k].decode('utf-8') + ' (' + k + ') ')
else:
top_comment = ElementTree.Comment(' ' + k + ' ')
top.append(top_comment)
child = SubElement(top, 'string-array')
child.attrib['name'] = 'languages_all'
if '*' not in COVERAGE_LIST:
# Iterate through only those codes in COVERAGE_LIST
for lang_code in COVERAGE_LIST:
if lang_code in english_pairs.keys():
comment = ElementTree.Comment(' ' + lang_code + ' - ' + english_pairs[lang_code].decode('utf-8') + ' ')
else:
comment = ElementTree.Comment(' ' + lang_code + ' ')
child.append(comment)
entry = SubElement(child, 'item')
if lang_code in v.keys():
entry.text = v[lang_code].decode('utf-8')
else:
entry.text = "UNDEFINED"
else:
# Iterate through all available language codes
for lang_code, lang_name in sorted(v.iteritems()):
if lang_code in english_pairs.keys():
comment = ElementTree.Comment(' ' + lang_code + ' - ' + english_pairs[lang_code].decode('utf-8') + ' ')
else:
comment = ElementTree.Comment(' ' + lang_code + ' ')
child.append(comment)
entry = SubElement(child, 'item')
entry.text = lang_name.decode('utf-8')
f.write(self.prettify(top))
示例8: _dict_to_xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def _dict_to_xml(self):
self._process_neighbor()
bgp_xml = Element('bgp')
as_xml = SubElement(bgp_xml, 'as-name')
as_xml.text = self.asn['name']
neighbor_xml = SubElement(bgp_xml, 'neighbor')
# Walk the OrderedDict neighbor in Reversed Order to generate XML with
# remote_ip in first position and remote_as in second position.
for field in reversed(self.neighbor):
if isinstance(map_fields.get(field), basestring):
child_xml = SubElement(neighbor_xml, map_fields[field])
child_xml.text = self._to_str(self.neighbor[field])
elif isinstance(map_fields.get(field), dict):
for child in map_fields[field]:
child_xml = self._create_or_get_element(neighbor_xml,
child)
child_of_child_xml = SubElement(child_xml,
map_fields[field][child])
child_of_child_xml.text = self._to_str(self.neighbor[field])
return tostring(bgp_xml)
示例9: addSoftKey
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def addSoftKey(self,index,label,uri):
softKey = SubElement(self.root, "SoftKey")
softKey.set("index",index)
label_key = SubElement(softKey,"Label")
label_key.text = label
uri_key = SubElement(softKey,"URI")
uri_key.text = uri
示例10: to_xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def to_xml(self):
'''write file:
tree.write("output.xml",encoding="ISO-8859-1", method="xml")
'''
survey = Element('survey')
title = SubElement(survey,'title')
title.text = self.title
description = SubElement(survey,'description')
description.text = self.description
# startDate = SubElement(survey,'startDate')
# startDate.text = str(self.startDate)
# endDate = SubElement(survey,'endDate')
# endDate.text = str(self.endDate)
maxNumberRespondents = SubElement(survey,'maxNumberRespondents')
maxNumberRespondents.text = str(self.maxNumberRespondents)
duration = SubElement(survey,'duration')
duration.text = str(self.duration)
for consent in self.consents:
survey.append(consent.to_xml())
for section in self.sections:
survey.append(section.to_xml())
tree = ET.ElementTree(survey)
return tree
示例11: __init__
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
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)
示例12: get_rgba_band
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def get_rgba_band(tmplt_band, tmplt_source, colours, levels, band_index):
"""Reclass to RGBA by a LUT (Look-Up Table)."""
band = deepcopy(tmplt_band)
source = deepcopy(tmplt_source)
band.set('band', str(band_index + 1))
colour_interp = SubElement(band, 'ColorInterp')
colour_interp.text = COLOUR_BAND_INTERP[band_index]
LUT = SubElement(source, 'LUT')
reduction = 1 - 1.0e-6 # factor to reduce limit by a minimal number
LUT.text = '%.6e:%i' % (levels[0] * reduction, colours[0][band_index])
for i in range(len(levels) - 1):
LUT.text += ',%.6e:%i' % (
levels[i],
colours[i + 1][band_index]
)
LUT.text += ',%.6e:%i' % (
levels[i + 1] * reduction,
colours[i + 1][band_index]
)
LUT.text += ',%.6e:%i' % (levels[-1], colours[-1][band_index])
band.append(source)
return band
示例13: addAddressXML
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def addAddressXML(self, root, serverInfo):
#adds the address XML with the source server information
#to the root XML tree. Input server information is a dict with
#following keys: "mhsid",'host','port','protocol','site'
# Returns element for address (in case additional info is required)
addressE = SubElement(root, 'address')
mhsidE = SubElement(addressE, 'mhsid')
mhsidE.text = serverInfo.get('mhsid', "?")
serverE = SubElement(addressE, 'server')
serverE.text = serverInfo.get('host', "?")
portE = SubElement(addressE, 'port')
portE.text = str(serverInfo.get('port', "?"))
protocolE = SubElement(addressE, 'protocol')
protocolE.text = str(serverInfo.get('protocol', "?"))
siteE = SubElement(addressE, 'site')
siteE.text = serverInfo.get('site', "?")
#optional components "location" "area" "welist"
if serverInfo.has_key('domain') and serverInfo['domain'] is not None:
d = serverInfo['domain']
locationE = SubElement(addressE, 'location', proj=d['proj'],
origx=str(d['origx']), origy=str(d['origy']),
extx=str(d['extx']), exty=str(d['exty']))
if serverInfo.has_key('area') and serverInfo['area'] is not None:
d = serverInfo['area']
areaE = SubElement(addressE, 'area', xdim=str(d['xdim']),
ydim=str(d['ydim']))
if serverInfo.has_key('parms') and serverInfo['parms'] is not None:
parms = serverInfo['parms']
self.addWelistXML(addressE, parms)
return addressE
示例14: to_xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def to_xml(self):
item = Element('item')
item.set('uid', self.uid)
if self.valid:
item.set('valid', 'yes')
else:
item.set('valid', 'no')
if self.autocomplete:
item.set('autocomplete', self.autocomplete)
if self.arg is not None:
item.set('arg', self.arg)
title = SubElement(item, 'title')
title.text = self.title
if self.subtitle is not None:
subtitle = SubElement(item, 'subtitle')
subtitle.text = self.subtitle
if self.icon is not None:
icon = SubElement(item, 'icon')
if isinstance(self.icon, dict):
icon.set('type', self.icon['type'])
icon.text = self.icon['path']
else:
icon.text = self.icon
return tostring(item)
示例15: _build_vcenter
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def _build_vcenter(vcenter_info):
"""
<VC xmlns="http://www.vmware.com/UM">
<hostname>10.255.79.5</hostname>
<username>root</username>
<password>vmware</password>
<monitor>true</monitor>
</VC>
:param vcenter_info:
:return:
"""
attribs = {
'xmlns': 'http://www.vmware.com/UM'
}
root = Element('vcServer', attribs)
host = SubElement(root, 'hostname')
host.text = str(vcenter_info['hostname'])
username = SubElement(root, 'username')
username.text = str(vcenter_info['username'])
password = SubElement(root, 'password')
password.text = str(vcenter_info['password'])
monitor = SubElement(root, 'monitor')
monitor.text = str(vcenter_info['monitor'])
return tostring(root)