本文整理汇总了Python中xml.etree.ElementTree.SubElement.append方法的典型用法代码示例。如果您正苦于以下问题:Python SubElement.append方法的具体用法?Python SubElement.append怎么用?Python SubElement.append使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree.SubElement
的用法示例。
在下文中一共展示了SubElement.append方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def xml(self):
""" Return IPFGraph as XML element
"""
graph = Element("IPFGraph")
block_tree = SubElement(graph, "Blocks")
for name in sorted(self.__blocks):
row, column = self.get_block_cell(name)
block_element = SubElement(block_tree, "Block",
{"name":name,
"grid_row":str(row),
"grid_column":str(column)})
block_element.append(self.__blocks[name].xml())
connection_tree = SubElement(graph, "Connections")
for connection in sorted(self.connections):
oport = connection._oport()
iport = connection._iport()
oblock = oport._owner_block()
iblock = iport._owner_block()
oblock_name = self.get_block_name(oblock)
iblock_name = self.get_block_name(iblock)
oport_name = oblock.get_port_name(oport)
iport_name = iblock.get_port_name(iport)
conection_element = SubElement(connection_tree, "Connection")
con_output = SubElement(conection_element,
"ConnectionOutput",
{"block" : oblock_name,
"port" : oport_name})
con_input = SubElement(conection_element,
"ConnectionInput",
{"block" : iblock_name,
"port" : iport_name})
return graph
示例2: execute
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [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))
示例3: adjust_visual_scenes
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def adjust_visual_scenes(self):
logging.info('Adjusting Visual Scenes.')
scenes = self.root.find('library_visual_scenes')
if scenes is None:
logging.error('No scenes.')
return
vis_scene = scenes[0]
root_nodes = list(vis_scene)
logging.info('Creating CryExport Node.')
cryexportnode = SubElement(vis_scene, 'node')
cryexportnode.attrib['id'] = 'CryExportNode_{0}'.format(self.config['scenename'])
extra = SubElement(cryexportnode, 'extra')
tech = SubElement(extra, 'technique', profile='CryEngine')
props = SubElement(tech, 'properties')
ft = 'fileType={0}'.format(self.config['filetype'])
flags = [ft]
if self.config['donotmerge']:
flags.append('DoNotMerge')
if self.config['customnormals']:
flags.append('CustomNormals')
if self.config['f32']:
flags.append('UseF32VertexFormat')
props.text = '\n\t\t'.join(flags)
logging.info('Applied flags "{0}" to CryExport Node.'.format(' '.join(flags)))
# Remove nodes.
for node in root_nodes:
vis_scene.remove(node)
cryexportnode.append(node)
logging.info('Reparented nodes.')
self.recursive_adjust_nodes(cryexportnode)
logging.info('Finished adjusting Visual Scenes.')
示例4: addLap
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def addLap(self, act):
st = Revolution.isoTimestamp(self.startsec)
lap = SubElement(act, 'Lap', {'StartTime': st})
last = len(self.points) - 1
tts = SubElement(lap, 'TotalTimeSeconds')
tts.text = str(self.points[last].secs)
dist = SubElement(lap, 'DistanceMeters')
dist.text = str(self.points[last].dist * 1000)
ms = SubElement(lap, 'MaximumSpeed')
ms.text = str(Revolution.metersPerSec(self.maxSpeed))
calories = SubElement(lap, 'Calories')
calories.text = str(self.points[last].calories)
avgheart = SubElement(lap, 'AverageHeartRateBpm')
avgheartvalue = SubElement(avgheart, 'Value')
avgheartvalue.text = str(self.ttlHeart / (last+1))
maxheart = SubElement(lap, 'MaximumHeartRateBpm')
maxheartvalue = SubElement(maxheart, 'Value')
maxheartvalue.text = str(self.maxHeart)
intensity = SubElement(lap, 'Intensity')
intensity.text = 'Active'
cadence = SubElement(lap, 'Cadence')
cadence.text = str(self.ttlCadence / (last+1))
trigger = SubElement(lap, 'TriggerMethod')
trigger.text = 'Manual'
lap.append(self.trackElement())
ext = SubElement(lap, 'Extensions')
self.LapExtension(ext, 'MaxBikeCadence', self.maxCadence)
avgspeed = Revolution.metersPerSec(self.ttlSpeed / (last+1))
self.LapExtension(ext, 'AvgSpeed', avgspeed)
avgwatts = self.ttlWatts / (last+1)
self.LapExtension(ext, 'AvgWatts', avgwatts)
self.LapExtension(ext, 'MaxWatts', self.maxWatts)
示例5: generateXML
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def generateXML(self, os):
# Structure of document is:
#
# <DAV:propertyupdate>
# <DAV:set>
# <<names/values of each property as elements>>
# </DAV:set>
# <DAV:remove>
# <<names of each property as elements>>
# </DAV:remove>
# </DAV:propertyupdate>
# <DAV:propertyupdate> element
propertyupdate = Element(davxml.propertyupdate)
# <DAV:set> element
if self.setprops:
set = SubElement(propertyupdate, davxml.set)
propel = SubElement(set, davxml.prop)
for prop in self.setprops:
propel.append(prop)
# <DAV:remove> element
if self.delprops:
remove = SubElement(propertyupdate, davxml.remove)
propel = SubElement(remove, davxml.prop)
for prop in self.delprops:
propel.append(prop)
# Now we have the complete document, so write it out (no indentation)
xmldoc = BetterElementTree(propertyupdate)
xmldoc.writeUTF8(os)
示例6: outputType
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def outputType(self, uri, graph):
self.typesCount += 1
typ = SubElement(self.dom,"owl:Class")
typ.set("rdf:about",uri)
ext = None
for (p,o) in graph.predicate_objects(uri):
if p == RDFS.label:
l = SubElement(typ,"rdfs:label")
l.set("xml:lang","en")
l.text = o
elif p == RDFS.comment:
c = SubElement(typ,"rdfs:comment")
c.set("xml:lang","en")
c.text = Markdown.parse(o)
elif p == RDFS.subClassOf:
s = SubElement(typ,"rdfs:subClassOf")
s.set("rdf:resource",o)
elif p == URIRef("http://schema.org/isPartOf"): #Defined in an extension
ext = str(o)
elif p == RDF.type and o == URIRef("http://schema.org/DataType"): #A datatype
s = SubElement(typ,"rdfs:subClassOf")
s.set("rdf:resource","http://schema.org/DataType")
typ.append(self.addDefined(uri,ext))
示例7: main
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def main(argv):
global lang
lang = argv[1] if len(argv) > 1 else 'none'
if lang == 'en':
outsvg = codecs.open(getScriptLoc() + '/../../public_html/en/img/droughtMovingAverage.svg','w+', 'utf-8')
elif lang == 'es':
outsvg = codecs.open(getScriptLoc() + '/../../public_html/es/img/droughtMovingAverage.svg','w+', 'utf-8')
else:
print 'You must specify language (en or es)'
return
svg = Element('svg')
svg.set('xmlns', 'http://www.w3.org/2000/svg')
svg.set('xmlns:xlink', 'http://www.w3.org/1999/xlink')
svg.set('viewBox', '0 0 600 320')
svg.set('preserveAspectRatio', 'xMinYMin meet')
global css
css = SubElement(svg, 'style')
css.set('type', 'text/css')
css.text = ''
css.text += 'text {font-family: Sans-Serif; pointer-events: none ;}'
css.text += '.linebox' + ':hover' + ' { opacity : .25 }'
script = SubElement(SubElement(svg,'body'), 'script')
scriptdat = ''
scriptdat += 'window.onload = function() {drawLines();};'
scriptdat += 'function drawLines() {line1 = document.getElementById("pline1");points1 = line1.getAttribute("points");line1.setAttribute("points", "");pointl1 = points1.split(" ");tpoints1 = [];allpoints1 = "";i21 = 0;for(i11 = 0; i11 < pointl1.length; i11++){allpoints1 += pointl1[i11] + " ";tpoints1[i11] = allpoints1;window.setTimeout(function() {line1.setAttribute("points", tpoints1[i21]); i21++;}, i11*25);} line1.setAttribute("points", tpoints1[i21] + "0,0"); line2 = document.getElementById("pline2");points2 = line2.getAttribute("points");line2.setAttribute("points", "");pointl2 = points2.split(" ");tpoints2 = [];allpoints2 = "";i22 = 0;for(i12 = 0; i12 < pointl2.length; i12++){allpoints2 += pointl2[i12] + " ";tpoints2[i12] = allpoints2;window.setTimeout(function() {line2.setAttribute("points", tpoints2[i22]); i22++;}, i12*25);}}'
script.append(Comment(' --><![CDATA[' + scriptdat.replace(']]>', ']]]]><![CDATA[>') + ']]><!-- '))
main = SubElement(svg, 'g')
graph = SubElement(main, 'g')
graph.set('transform', 'translate(65 10)')
renderGraph(graph, getScriptLoc() + '/../../src_data/flow10yrProcessed.csv')
renderLabels(main)
outsvg.truncate()
outsvg.write(fixIndentation(svg))
outsvg.close()
示例8: export_node
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def export_node(self, parent, node):
# import pdb; pdb.set_trace()
files = []
nodetag = SubElement(parent, "node",
dict(id=str(node.pk), tree_path=node.tree_path))
for content in node.contentbase.all():
## transform the baseclass into the actual instance
content = content.content()
spoke = content.spoke()
type = spoke.model.get_name()
xmlcontent = SubElement(nodetag, "content",
dict(slug=node.slug(content.language),
type=type))
contentxml, files = spoke.serializer().serialize(spoke)
xmlcontent.append(contentxml)
children = SubElement(nodetag, "children")
for child in node.children():
files += self.export_node(children, child)
return files
示例9: write_instances
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def write_instances(self, layer_element, layer):
"""Write out the instances in a layer"""
instances_element = SubElement(layer_element, 'instances')
for inst in layer.getInstances():
position = inst.getLocationRef().getExactLayerCoordinates()
attrib = {
'o': inst.getObject().getId(),
'x': str(position.x),
'y': str(position.y),
'z': str(position.z),
'r': str(inst.getRotation()),
}
namespace = inst.getObject().getNamespace()
if namespace != self.namespace:
attrib['ns'] = inst.getObject().getNamespace()
self.namespace = namespace
inst_id = inst.getId()
if inst_id:
attrib['id'] = inst_id
if inst_id is not None and inst_id in loaders.data.objects:
for key in loaders.data.objects[inst_id]:
if key not in attrib and loaders.data.objects[inst_id][key]:
print key
attrib[key] = str(loaders.data.objects[inst_id][key])
print key, attrib[key]
# the local_loader loader sets object_type as type, we have to
# correct for that here but really we should fix that there
if attrib.get('type'):
attrib['object_type'] = attrib['type']
del attrib['type']
instances_element.append(Element('i', attrib))
示例10: genResultXml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def genResultXml(resultList, device, Start, End):
try:
print "Generate test.result.xml ---------------->Start"
tree = ElementTree()
root = Element("test_definition")
tree._setroot(root)
env = Element("environment", {"build_id":"","device_id":"","device_name":"","host":"",\
"lite_version":"","manufacturer":"","resolution":"","screen_size":""})
root.append(env)
#summary element
summary = Element("summary", {"test_plan_name":""})
root.append(summary)
tStart = SE(summary, "start_at")
tEnd = SE(summary, "end_at")
tStart.text = Start
tEnd.text = End
#suite element
suite = SE(root, "suite", {"category":"Runtime_Core","launcher":"xwalk",\
"name":"wrt-manifest-android-tests"})
setPositive = SE(suite, "set", {"name":"positive","set_debug_msg":""})
setNegitive = SE(suite, "set", {"name":"negative","set_debug_msg":""})
#testcase element
for case in resultList:
setElement = setPositive
if case["set"] == "negative":
setElement = setNegitive
pur = "Check if packaged web application can be installed/launched/uninstalled successfully"
testcase = SE(setElement, "testcase", {"component":"Runtime Core",\
"execution_type":"auto","id":case["id"],"purpose":pur,"result":case["result"]})
desc = SE(testcase, "description")
entry = Element("test_script_entry")
entry.text = case["entry"].decode("utf-8")
desc.append(entry)
resultInfo = SE(testcase, "result_info")
actualResult = SE(resultInfo, "actual_result")
actualResult.text = case["result"]
caseStart = SE(resultInfo, "start")
caseStart.text = case["start"]
caseEnd = SE(resultInfo, "end")
caseEnd.text = case["end"]
stdOut = SE(resultInfo, "stdout")
if case["result"] == "FAIL":
stdOut.text = "[message]\n" + case["message"].decode("utf-8")
else:
stdOut.text = "[message]"
SE(resultInfo, "stderr")
tree.write(ConstPath + "/device_" + device + "/report/wrt-manifest-android-tests.xml")
updateXmlTitle(ConstPath + "/device_" + device + "/report/wrt-manifest-android-tests.xml",'<?xml version="1.0" encoding="UTF-8"?>\n<?xml-stylesheet type="text/xsl" href="./style/testresult.xsl"?>\n<?xml-stylesheet type="text/xsl" href="testresult.xsl"?>\n')
print "Generate test.result.xml ---------------->O.K"
except Exception,e:
print Exception,":",e
print "Generate test.result.xml ---------------->Error"
sys.exit(1)
示例11: EmitXML
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def EmitXML(self):
dvd_elem = Element('dvd',
attrib=dict(folder=str(self.folder), series=str(self.series),
season=str(self.season)))
titles_elem = SubElement(dvd_elem, 'titles')
for title in self.titles:
titles_elem.append(title.EmitXML())
return dvd_elem
示例12: _saveFactories
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def _saveFactories(self, factories):
element = Element("factories")
sources = SubElement(element, "sources")
for factory in factories:
if isinstance(factory, SourceFactory):
source_element = self._saveSource(factory)
sources.append(source_element)
return element
示例13: to_xml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def to_xml(self, parent):
#Remove any keys with value None
xml_attribs = {key: str(value) for key, value in self.attribs.iteritems()
if value != None}
#XML elment representing this object
elem = SubElement(parent, self.type, xml_attribs)
#VPR's xml parser is very picky, it does not allow mixing the ordering of xml tags
# This works:
# <!--- This ordering is ok, all of the direct tags finish
# before the complete tags start -->
# <direct name='direct1" ... />
# <direct name='direct2" ... />
# <complete name='complete1" ... />
#
# This does NOT works:
# <!--- The complete tags start before the direct tags have finished
# this will cause a segfault in the architecture parser -->
# <direct name='direct1" ... />
# <complete name='complete1" ... />
# <direct name='direct2" ... />
#
# Therefore sort all the child elements by type and add them to the tree in order
children_by_type = {}
for child in self.children:
if child.type not in children_by_type:
#New type add a list for it
children_by_type[child.type] = []
#Add the child to its type list
children_by_type[child.type].append(child)
#Attach children finishing each type before starting the next (builds xml tree)
# For readability purposes preferentially process the types in the following order
preferred_order = ['input', 'output', 'clock', 'T_setup', 'T_clock_to_Q', 'pb_type', 'interconnect', 'complete', 'mux', 'direct']
for type in preferred_order:
if type in children_by_type:
for child in children_by_type[type]:
child.to_xml(elem)
#This type has been processed, so delete it
# This allows us to still process any items
# not in the preferred_order list, without
# repeating any types that ARE in the
# preferred_order list
del children_by_type[type]
#Catch any types not in the preferred_order list
for type, child_type_list in children_by_type.iteritems():
for child in child_type_list:
child.to_xml(elem)
#Add a comment attribute
if self.comment != None:
elem.append(Comment(self.comment))
return elem
示例14: menuItemCoursesXML
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def menuItemCoursesXML():
courses = db.getAllCourses()
xml = Element('restaurants')
child = SubElement(xml, 'courses')
for course in courses:
child.append(course.serialize_xml)
return xmlResponse(xml)
示例15: buildSoapResponse
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import append [as 别名]
def buildSoapResponse(response, body):
# construct the soap response, and serialize it
envelope = Element('{%s}Envelope' % cocy.soaplib.ns_soap_env)
# body
soap_body = SubElement(envelope, '{%s}Body' % cocy.soaplib.ns_soap_env)
soap_body.append(body)
response.headers["Content-Type"] = "text/xml; charset=utf-8"
return "<?xml version='1.0' encoding='utf-8'?>" + \
ElementTree.tostring(envelope, encoding="utf-8")