本文整理汇总了Python中xml.etree.ElementTree.SubElement.attrib['name']方法的典型用法代码示例。如果您正苦于以下问题:Python SubElement.attrib['name']方法的具体用法?Python SubElement.attrib['name']怎么用?Python SubElement.attrib['name']使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree.SubElement
的用法示例。
在下文中一共展示了SubElement.attrib['name']方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib['name'] [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))
示例2: serialize
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib['name'] [as 别名]
def serialize(self, spoke):
o = spoke.instance
files = []
fields = {}
for field in o._meta.concrete_model._meta.fields:
handler = getattr(self, "serialize_%s" % field.name, None)
if field.name in self.skip:
continue
if handler:
fields[field.name] = handler(field, o)
elif field.serialize:
if field.rel is None:
value = field.value_to_string(o)
else:
value = getattr(o, field.get_attname())
value = smart_unicode(value)
fields[field.name] = value
if isinstance(field, FileField):
files.append(value)
for e in self.extra:
handler = getattr(self, "serialize_extra_%s" % e, None)
if handler:
fields[e] = handler(e, o)
## tags arent fields but a manager, handle
## separately
xmlfields = Element("fields")
for k, v in fields.iteritems():
if isinstance(v, dict):
tag = v['name']
value = v['value']
e = SubElement(xmlfields, tag)
try:
for vv in value:
SubElement(e, vv['name']).text = vv['value']
except TypeError: # not a sequence
e.text = value
else:
e = SubElement(xmlfields, "field")
e.attrib['name'] = k
e.text = v
return xmlfields, files
示例3: xml_config
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib['name'] [as 别名]
def xml_config(self, fields, target_fields, dirpath, csv_database):
root = etree.Element('duke')
schema = SubElement(root, 'schema')
threshold = etree.Element('threshold')
threshold.text = "0.9"
schema.append(threshold)
maybethreshold = etree.Element('maybe-threshold')
maybethreshold.text = "0.5"
schema.append(maybethreshold)
for elem in fields:
if elem[0] == "id":
property = etree.Element('property')
property.attrib['type'] = "id"
name = SubElement(property, 'name')
name.text = elem[0]
schema.append(property)
else:
property = etree.Element('property')
if elem[0] in target_fields:
property.attrib['lookup'] = "true"
else:
property.attrib['lookup'] = "false"
name = SubElement(property, 'name')
name.text = elem[0]
comparator = SubElement(property, 'comparator')
comparator.text = elem[2]
low = SubElement(property, 'low')
low.text = elem[3]
high = SubElement(property, 'high')
high.text = elem[4]
schema.append(property)
#файл
csv = etree.Element('csv')
param = SubElement(csv, 'param')
param.attrib['name'] = 'input-file'
param.attrib['value'] = csv_database
#разделитель
param = SubElement(csv, 'param')
param.attrib['name'] = 'separator'
param.attrib['value'] = ','
for elem in fields:
if elem[0] == "id":
column = SubElement(csv, 'column')
column.attrib['name'] = elem[0]
column.attrib['property'] = elem[0]
else:
column = SubElement(csv, 'column')
column.attrib['name'] = elem[0]
column.attrib['property'] = elem[0]
column.attrib['cleaner'] = elem[1]
root.append(csv)
s = etree.tostring(root, pretty_print=True)
with open("%s/xmlconfig.xml" % dirpath, "w") as xmlfile:
xmlfile.write(s)
print s
print("\n")
示例4: main
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib['name'] [as 别名]
def main():
if len(sys.argv) not in [3,4]:
print '==============================================================================='
print 'AddUnlabeledSchemeToResidueType.py reads in a cara repository file and modifies'
print 'the residue-type definitions to include a labeling scheme with N14 and C12.'
print 'A labeling scheme called \'unlabeled\' is added for this purpose.'
print ''
print 'Usage: AddUnlabeledSchemeToResidueType.py infile.cara outfile.cara'
print 'Number of arguments given: %d'%(len(sys.argv)-1)
print 'An optional third argument names which project to modify, if'
print 'there is more than one project in a repository. '
print '=============================================================================='
return
infile = sys.argv[1]
outfile = sys.argv[2]
if exists(outfile):
print '\nOutput file \'%s\' exists. Choose a new name to avoid overwriting.\n'%outfile
return
tree = ET.parse(infile)
root = tree.getroot()
projects = root.findall('project')
# Select a project according to command-line input, defaulting to the first project
if len(sys.argv) == 4:
projectName = sys.argv[3]
project = getProject(projectName,projects)
if not project:
print 'No project found with name \"%s\".'%projectName
return
else:
project = projects[0]
if not project:
print 'No project found.'
return
# Find existing schemes & make a new one by incrementing the highest existing ID number
library = root.find('library')
schemes = library.findall('scheme')
numSchemes = len(schemes)
if numSchemes > 0:
schemeIDs = [int(scheme.get('id')) for scheme in schemes]
schemeIDs.sort()
newIDnum = schemeIDs[numSchemes-1]+1
newID = '%d'%newIDnum
else:
newID = '1'
newscheme = SubElement(library,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['name'] = 'unlabeled%s'%newID
# Modify residue-type
residueTypes = library.findall('residue-type')
for residueType in residueTypes:
atoms = residueType.findall('atom')
for atom in atoms:
if atom.get('name')[0]=='N':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['type'] = 'N14'
elif atom.get('name')[0]=='C':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['type'] = 'C12'
tree.write(outfile)
示例5: xmlSetup
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib['name'] [as 别名]
def xmlSetup(self, logType, logList):
"""Create xml file with fields from logbook form."""
from xml.etree.ElementTree import Element, SubElement, ElementTree
from datetime import datetime
curr_time = datetime.now()
if logType == "MCC":
# Set up xml tags
log_entry = Element('log_entry')
title = SubElement(log_entry, 'title')
program = SubElement(log_entry, 'program')
timestamp = SubElement(log_entry, 'timestamp')
priority = SubElement(log_entry, 'priority')
os_user = SubElement(log_entry, 'os_user')
hostname = SubElement(log_entry, 'hostname')
text = SubElement(log_entry, 'text')
log_user = SubElement(log_entry, 'log_user')
# Check for multiple logbooks and parse into seperate tags
logbook = []
for i in range(len(logList)):
logbook.append(SubElement(log_entry, 'logbook'))
logbook[i].text = logList[i].lower()
# Take care of dummy, unchanging tags first
log_entry.attrib['type'] = "LOGENTRY"
program.text = "152"
priority.text = "NORMAL"
os_user.text = "nobody"
hostname.text = "mccelog"
text.attrib['type'] = "text/plain"
# Handle attachment if image exists
if not self.imagePixmap.isNull():
attachment = SubElement(log_entry, 'attachment')
attachment.attrib['name'] = "Figure 1"
attachment.attrib['type'] = "image/" + self.imageType
attachment.text = curr_time.strftime("%Y%m%d_%H%M%S_") + str(curr_time.microsecond) + "." + self.imageType
# Set timestamp format
timestamp.text = curr_time.strftime("%Y/%m/%d %H:%M:%S")
fileName = "/tmp/" + curr_time.strftime("%Y%m%d_%H%M%S_") + str(curr_time.microsecond) + ".xml"
else: # If using Physics logbook
timeString = curr_time.strftime("%Y-%m-%dT%H:%M:%S")
# Set up xml tags
log_entry = Element(None)
severity = SubElement(log_entry, 'severity')
location = SubElement(log_entry, 'location')
keywords = SubElement(log_entry, 'keywords')
time = SubElement(log_entry, 'time')
isodate = SubElement(log_entry, 'isodate')
log_user = SubElement(log_entry, 'author')
category = SubElement(log_entry, 'category')
title = SubElement(log_entry, 'title')
metainfo = SubElement(log_entry, 'metainfo')
# Handle attachment if image exists
if not self.imagePixmap.isNull():
imageFile = SubElement(log_entry, 'link')
imageFile.text = timeString + "-00." + self.imageType
thumbnail = SubElement(log_entry, 'file')
thumbnail.text = timeString + "-00.png"
text = SubElement(log_entry, 'text') # Logbook expects Text tag to come last (for some strange reason)
# Take care of dummy, unchanging tags first
log_entry.attrib['type'] = "LOGENTRY"
category.text = "USERLOG"
location.text = "not set"
severity.text = "NONE"
keywords.text = "none"
time.text = curr_time.strftime("%H:%M:%S")
isodate.text = curr_time.strftime("%Y-%m-%d")
metainfo.text = timeString + "-00.xml"
fileName = "/tmp/" + metainfo.text
# Fill in user inputs
log_user.text = str(self.logui.userName.text())
title.text = str(self.logui.titleEntry.text())
if title.text == "":
QMessageBox().warning(self, "No Title entered", "Please enter a title for the entry...")
return None
text.text = str(self.logui.textEntry.toPlainText())
# If text field is truly empty, ElementTree leaves off tag entirely which causes logbook parser to fail
if text.text == "":
text.text = " "
# Create xml file
xmlFile = open(fileName, "w")
if logType == "MCC":
ElementTree(log_entry).write(xmlFile)
else:
#.........这里部分代码省略.........
示例6: Element
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib['name'] [as 别名]
__author__ = 'ravi'
from xml.etree.ElementTree import ElementTree, Element, SubElement
from sys import stdout
root_tag = Element('directories')
directory_tag = SubElement(root_tag, 'directory')
directory_tag.attrib['name'] = '/home/ravi'
file_tag1 = SubElement(directory_tag, 'file')
file_tag1.text = 'sample.pdf'
et = ElementTree(root_tag)
et.write('test.xml')
示例7: main
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib['name'] [as 别名]
def main():
if len(sys.argv) not in [3,4]:
print '==============================================================================='
print 'AddILVlabelingScheme.py reads in a cara repository file and modifies the'
print 'residue-type definitions to include a labeling scheme with 12C and 2H'
print 'except at methyl groups of I, L, and V.'
print ''
print 'A labeling scheme called \'ILVnoesy\' is added for this purpose.'
print ''
print 'Usage: AddILVlabelingScheme.py infile.cara outfile.cara'
print 'Number of arguments given: %d'%(len(sys.argv)-1)
print 'An optional third argument names which project to modify, if'
print 'there is more than one project in a repository. '
print '=============================================================================='
return
infile = sys.argv[1]
outfile = sys.argv[2]
if infile == outfile:
print '\nPlease do not overwrite your original file. Try again.\n'
return
tree = ET.parse(infile)
root = tree.getroot()
projects = root.findall('project')
# Select a project according to command-line input, defaulting to the first project
if len(sys.argv) == 4:
projectName = sys.argv[3]
project = getProject(projectName,projects)
if not project:
print 'No project found with name \"%s\".'%projectName
return
else:
project = projects[0]
if not project:
print 'No project found.'
return
# Find existing schemes & make a new one by incrementing the highest existing ID number
library = root.find('library')
schemes = library.findall('scheme')
numSchemes = len(schemes)
if numSchemes > 0:
schemeIDs = [int(scheme.get('id')) for scheme in schemes]
schemeIDs.sort()
newIDnum = schemeIDs[numSchemes-1]+1
newID = '%d'%newIDnum
else:
newID = '1'
newscheme = SubElement(library,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['name'] = 'ILVnoesy15N-%s'%newID
# Modify residue-type
residueTypes = library.findall('residue-type')
for residueType in residueTypes:
if residueType.get('letter') not in ('I','L','V'):
atoms = residueType.findall('atom')
for atom in atoms:
if atom.get('name')[0]=='C':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['type'] = 'C12'
elif atom.get('name')[0]=='H' and atom.get('name')!='H':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['type'] = 'H2'
elif residueType.get('letter')=='L':
atoms = residueType.findall('atom')
for atom in atoms:
if atom.get('name')[0]=='C' and atom.get('name')[0:2]!='CD':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['type'] = 'C12'
elif atom.get('name')[0]=='H' and atom.get('name')[0:2]!='HD' and atom.get('name')!='H':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['type'] = 'H2'
elif residueType.get('letter')=='V':
atoms = residueType.findall('atom')
for atom in atoms:
if atom.get('name')[0]=='C' and atom.get('name')[0:2]!='CG':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['type'] = 'C12'
elif atom.get('name')[0]=='H' and atom.get('name')[0:2]!='HG' and atom.get('name')!='H':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
newscheme.attrib['type'] = 'H2'
elif residueType.get('letter')=='I':
atoms = residueType.findall('atom')
for atom in atoms:
if atom.get('name')[0]=='C' and atom.get('name')[0:2]!='CD':
newscheme = SubElement(atom,'scheme')
newscheme.attrib['id'] = newID
#.........这里部分代码省略.........
示例8: encode_as_tmx
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import attrib['name'] [as 别名]
def encode_as_tmx(level, tileset_path):
root = Element('map')
set_attrs(root, {
"version" : "1.0",
"orientation" : "orthogonal",
"renderorder" : "right-down",
"width" : 64,
"height" : 64,
"tilewidth" : 16,
"tileheight" : 16,
"nextobjectid" : 1
})
tileset = SubElement(root, 'tileset')
set_attrs(tileset, {
"firstgid" : 1,
"source" : tileset_path,
})
ext_start = 32*128 + 1
npc_tileset = SubElement(root, 'tileset')
set_attrs(npc_tileset, {
"firstgid" : ext_start,
"name" : "extra images",
})
map_layer = SubElement(root, 'layer')
set_attrs(map_layer, {
"name" : "map",
"width" : 64,
"height" : 64,
})
data = SubElement(map_layer, 'data')
data.attrib['encoding'] = "csv"
data.text = encode_as_csv(level)
scope = {
"images" : {},
"next_gid" : 0,
"ext_start" : ext_start,
}
def index_for_img(src):
if not scope['images'].has_key(src):
scope['images'][src] = scope['ext_start'] + scope['next_gid']
tile = SubElement(npc_tileset, 'tile')
tile.attrib['id'] = str(scope['next_gid'])
scope['next_gid'] += 1
img = SubElement(tile, 'image')
img.attrib['source'] = relative_img_path(src)
return scope['images'][src]
npc_layer = SubElement(root, 'objectgroup')
npc_layer.attrib['name'] = "npcs"
obj_id = 0
for actor in level.actors:
if not actor.image:
continue
obj_id += 1
obj = SubElement(npc_layer, 'object')
set_attrs(obj, {
"id" : obj_id,
"gid" : index_for_img(actor.image),
"name" : actor.image.split("/")[-1],
"x" : actor.x*16,
"y" : actor.y*16 + actor.clip[3],
})
link_layer = SubElement(root, 'objectgroup')
link_layer.attrib['name'] = "level links"
link_layer.attrib['color'] = "#ffff00"
for link in level.links:
obj_id += 1
obj = SubElement(link_layer, 'object')
set_attrs(obj, {
"id" : obj_id,
"name" : link.target,
"type" : "link",
"x" : link.area[0] * 16,
"y" : link.area[1] * 16,
"width" : link.area[2] * 16,
"height" : link.area[3] * 16,
})
props = SubElement(obj, 'properties')
target = SubElement(props, 'property')
set_attrs(target, {
"name" : "warp target",
"type" : "string",
"value" : link.target,
})
dest_x = SubElement(props, 'property')
set_attrs(dest_x, {
"name" : "destination x",
"type" : "string",
"value" : link.dest[0],
})
dest_y = SubElement(props, 'property')
set_attrs(dest_y, {
#.........这里部分代码省略.........