def formatAlertsCount(numberofalerts, outformat):
""" Create XML / Json Structure with number of Alerts in requested timespan """
if outformat == "xml":
ewssimpleinfo = ET.Element('EWSSimpleIPInfo')
alertCount = ET.SubElement(ewssimpleinfo, 'AlertCount')
if numberofalerts:
alertCount.text = str(numberofalerts)
else:
alertCount.text = str(0)
prettify(ewssimpleinfo)
alertcountxml = '<?xml version="1.0" encoding="UTF-8"?>'
alertcountxml += (ET.tostring(ewssimpleinfo, encoding="utf-8", method="xml")).decode('utf-8')
return alertcountxml
else:
return ({'AlertCount': numberofalerts})
python类SubElement()的实例源码
def _set_boot_device(conn, domain, device):
"""Set the boot device.
:param conn: active libvirt connection.
:param domain: libvirt domain object.
:raises: LibvirtError if failed update domain xml.
"""
parsed = ET.fromstring(domain.XMLDesc())
os = parsed.find('os')
boot_list = os.findall('boot')
# Clear boot list
for boot_el in boot_list:
os.remove(boot_el)
boot_el = ET.SubElement(os, 'boot')
boot_el.set('dev', device)
try:
conn.defineXML(ET.tostring(parsed))
except libvirt.libvirtError as e:
raise isd_exc.LibvirtError(err=e)
parameterwidgets.py 文件源码
项目:SLP-Annotator
作者: PhonologicalCorpusTools
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def exportXML(self):
elements = list()
for node in anytree.PreOrderIter(self.tree):
nodeName = parameters.encodeXMLName(node.name)
if not elements:
top = xmlElement(self.tree.name)
top.attrib['name'] = self.tree.name
top.attrib['is_checked'] = 'False'
top.attrib['is_default'] = 'False'
elements.append(top)
continue
for e in elements:
if e.attrib['name'] == node.parent.name:
se = xmlSubElement(e, nodeName)
se.attrib['name'] = node.name
se.attrib['is_checked'] = 'True' if node.is_checked else 'False'
se.attrib['is_default'] = 'True' if node.is_default else 'False'
se.attrib['parent'] = e.attrib['name']
elements.append(se)
break
# else:
# print('could not find parent for {}'.format(node.name))
string = xmlElementTree.tostring(top, encoding='unicode', method='xml')
return string
def to_xml(self):
"""Produces an XML out of the point data. Disregards the "action" field."""
el = etree.Element(self.osm_type, id=str(self.osm_id), version=str(self.version))
for tag, value in self.tags.items():
etree.SubElement(el, 'tag', k=tag, v=value)
if self.osm_type == 'node':
el.set('lat', str(self.lat))
el.set('lon', str(self.lon))
elif self.osm_type == 'way':
for node_id in self.members:
etree.SubElement(el, 'nd', ref=str(node_id))
elif self.osm_type == 'relation':
for member in self.members:
m = etree.SubElement(el, 'member')
for i, n in enumerate(('type', 'ref', 'role')):
m.set(n, str(member[i]))
return el
def gen_xml(self, xml_parent, data):
definition = data.get(self.component_type, {})
scm_definition = 'scm' in definition
definition_type = 'CpsScmFlowDefinition' if scm_definition else 'CpsFlowDefinition'
xml_definition = XML.SubElement(
xml_parent,
'definition',
{
'plugin': 'workflow-cps',
'class': 'org.jenkinsci.plugins.workflow.cps.' + definition_type
}
)
if scm_definition:
scm_module = next(module for module in self.registry.modules if isinstance(module, SCM))
scm_module.gen_xml(xml_definition, definition)
XML.SubElement(xml_definition, 'scriptPath').text = definition.get('script-path', 'Jenkinsfile')
else:
XML.SubElement(xml_definition, 'script').text = definition.get('script', '')
XML.SubElement(xml_definition, 'sandbox').text = str(definition.get('sandbox', False)).lower()
def generate_xml(self, parent):
"""
Generates the XML element for this node.
:param xml.etree.ElementTree.Element parent: The parent XML element.
"""
command_job = SubElement(parent, 'CommandJob')
self._generate_xml_common(command_job)
path = SubElement(command_job, 'Path')
path.text = self.path
if self.args:
args_element = SubElement(command_job, 'Args')
for arg in self.args:
argument = SubElement(args_element, 'Arg')
argument.text = str(arg)
# ------------------------------------------------------------------------------------------------------------------
def UrhoWriteTriggers(triggersList, filename, fOptions):
triggersElem = ET.Element('animation')
for trigger in triggersList:
triggerElem = ET.SubElement(triggersElem, "trigger")
if trigger.time is not None:
triggerElem.set("time", FloatToString(trigger.time))
if trigger.ratio is not None:
triggerElem.set("normalizedtime", FloatToString(trigger.ratio))
# We use a string variant, for other types See typeNames[] in Variant.cpp
# and XMLElement::GetVariant()
triggerElem.set("type", "String")
triggerElem.set("value", str(trigger.data))
WriteXmlFile(triggersElem, filename, fOptions)
#--------------------
# Utils
#--------------------
# Search for the most complete element mask
def export(self, filename):
self.nodes, self.renderer = self.compute()
initWidth, initHeight = (self.options['initialWidth'],
self.options['initialHeight'])
doc = ElementTree.Element('svg', width=str(initWidth),
height=str(initHeight))
transform = self.getTranslation()
trans = ElementTree.SubElement(doc, 'g', transform=transform)
ElementTree.SubElement(trans, 'g', attrib={'class': 'dummy-layer'})
mainLayer = self.add_main(trans)
self.add_timeline(mainLayer)
if self.options['showTicks']:
self.add_axis(mainLayer)
self.add_links(mainLayer)
self.add_labels(mainLayer)
self.add_dots(mainLayer)
svglines = ElementTree.tostring(doc)
with open(filename, 'wb') as fid:
fid.write(svglines)
return svglines
def writeXML(dataObj, fname, dtdPath):
if dataObj.predSev == 0:
sev = "ABSENT"
elif dataObj.predSev == 1:
sev = "MILD"
elif dataObj.predSev == 2:
sev = "MODERATE"
elif dataObj.predSev == 3:
sev = "SEVERE"
root = ET.Element("RDoC")
ET.SubElement(root, "TEXT").text = dataObj.text.content
tags = ET.SubElement(root, "TAGS")
pos_val = ET.SubElement(tags, "POSITIVE_VALENCE")
pos_val.set('score', sev)
pos_val.set('annotated_by', dataObj.Nannotators)
tree = ET.ElementTree(root)
tree.write(fname)
def pSuite_testcase(resultfile, classname, name, time):
global currentTestSuitePointer
global currentTestCasePointer
global gTestSuite
global gTestSuiteLoop
global gTestCase
global gTestCaseLoop
gTestCase[gTestCaseLoop] = ET.SubElement(currentTestSuitePointer,"testcase")
gTestCase[gTestCaseLoop].set('classname',classname)
gTestCase[gTestCaseLoop].set('name',name)
gTestCase[gTestCaseLoop].set('time',time)
currentTestCasePointer = gTestCase[gTestCaseLoop]
printOutput()
database_utils_class.py 文件源码
项目:warriorframework
作者: warriorframework
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def convert_tddict_to_xmlobj(self, root, tddict):
"""
To Convert the testdata dictionary into a xml object.
Testdata dictionary can have following combinations :
1. dict within dict
2. list within dict
3. dict within list
"""
for element in tddict:
if isinstance(tddict[element], dict):
self.convert_tddict_to_xmlobj(ET.SubElement(root, element),
tddict[element])
elif isinstance(tddict[element], list):
for list_elem in tddict[element]:
# here list can only have dictionary in it
if isinstance(list_elem, dict):
self.convert_tddict_to_xmlobj(ET.SubElement(root,
element),
list_elem)
else:
root.set(element, tddict[element])
def setInterfaceBandwidth(self,instance,port,bandwidth):
'''????'''
domXml = instance.XMLDesc(0)
root = ElementTree.fromstring(domXml)
try:
for dev in root.findall('.//devices/'):
if dev.tag == 'interface':
for iter in dev:
if iter.tag == 'target' and iter.get('dev') == port:
bwXml = ElementTree.SubElement(dev,'bandwidth')
inbdXml = ElementTree.Element('inbound')
inbdXml.set('average',str(int(bandwidth)*1024))
inbdXml.set('peak',str(int(bandwidth)*1024))
inbdXml.set('burst','1024')
outbdXml = ElementTree.Element('outbound')
outbdXml.set('average',str(int(bandwidth)*1024))
outbdXml.set('peak',str(int(bandwidth)*1024))
outbdXml.set('burst','1024')
bwXml.append(inbdXml)
bwXml.append(outbdXml)
domXml = ElementTree.tostring(root)
except Exception,e:
return {"status":"faild",'data':e}
if self.defineXML(domXml):return {"status":"success",'data':None}
def attach_page_style(self, el):
"""Attach the default page style.
Create an automatic-style that refers to the current style
of this element and that refers to the default page style.
"""
current_style = el.get('text:style-name')
style_name = 'P1003'
el1 = SubElement(
self.automatic_styles, 'style:style', attrib={
'style:name': style_name,
'style:master-page-name': "rststyle-pagedefault",
'style:family': "paragraph",
}, nsdict=SNSD)
if current_style:
el1.set('style:parent-style-name', current_style)
el.set('text:style-name', style_name)
def visit_enumerated_list(self, node):
el1 = self.current_element
if self.blockstyle == self.rststyle('blockquote'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-enumlist'),
})
self.list_style_stack.append(self.rststyle('blockquote-enumitem'))
elif self.blockstyle == self.rststyle('highlights'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-enumlist'),
})
self.list_style_stack.append(self.rststyle('highlights-enumitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-enumlist'),
})
self.list_style_stack.append(self.rststyle('epigraph-enumitem'))
else:
liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), )
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle(liststylename),
})
self.list_style_stack.append(self.rststyle('enumitem'))
self.set_current_element(el2)
def visit_inline(self, node):
styles = node.attributes.get('classes', ())
if styles:
el = self.current_element
for inline_style in styles:
el = SubElement(el, 'text:span',
attrib={'text:style-name':
self.rststyle(inline_style)})
count = len(styles)
else:
# No style was specified so use a default style (old code
# crashed if no style was given)
el = SubElement(self.current_element, 'text:span')
count = 1
self.set_current_element(el)
self.inline_style_count_stack.append(count)
def visit_colspec(self, node):
self.column_count += 1
colspec_name = self.rststyle(
'%s%%d.%%s' % TABLESTYLEPREFIX,
(self.table_count, chr(self.column_count), )
)
colwidth = node['colwidth'] / 12.0
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': colspec_name,
'style:family': 'table-column',
}, nsdict=SNSD)
el1_1 = SubElement(el1, 'style:table-column-properties', attrib={
'style:column-width': '%.4fin' % colwidth
},
nsdict=SNSD)
el2 = self.append_child('table:table-column', attrib={
'table:style-name': colspec_name,
})
self.table_width += colwidth
def _serialize_type_structure(self, xmlnode, params, shape, name):
structure_node = ElementTree.SubElement(xmlnode, name)
if 'xmlNamespace' in shape.serialization:
namespace_metadata = shape.serialization['xmlNamespace']
attribute_name = 'xmlns'
if namespace_metadata.get('prefix'):
attribute_name += ':%s' % namespace_metadata['prefix']
structure_node.attrib[attribute_name] = namespace_metadata['uri']
for key, value in params.items():
member_shape = shape.members[key]
member_name = member_shape.serialization.get('name', key)
# We need to special case member shapes that are marked as an
# xmlAttribute. Rather than serializing into an XML child node,
# we instead serialize the shape to an XML attribute of the
# *current* node.
if value is None:
# Don't serialize any param whose value is None.
return
if member_shape.serialization.get('xmlAttribute'):
# xmlAttributes must have a serialization name.
xml_attribute_name = member_shape.serialization['name']
structure_node.attrib[xml_attribute_name] = value
continue
self._serialize(member_shape, value, structure_node, member_name)
def _serialize_type_map(self, xmlnode, params, shape, name):
# Given the ``name`` of MyMap, and input of {"key1": "val1"}
# we serialize this as:
# <MyMap>
# <entry>
# <key>key1</key>
# <value>val1</value>
# </entry>
# </MyMap>
node = ElementTree.SubElement(xmlnode, name)
# TODO: handle flattened maps.
for key, value in params.items():
entry_node = ElementTree.SubElement(node, 'entry')
key_name = self._get_serialized_name(shape.key, default_name='key')
val_name = self._get_serialized_name(shape.value,
default_name='value')
self._serialize(shape.key, key, entry_node, key_name)
self._serialize(shape.value, value, entry_node, val_name)
def create_xml_page(dictionary: dict, creator_name='DocSeg') -> 'Page':
page = Page.from_dict(dictionary)
# Create xml
root = ET.Element('PcGts')
root.set('xmlns', _ns['p'])
# Metadata
generated_on = str(datetime.datetime.now())
metadata = ET.SubElement(root, 'Metadata')
creator = ET.SubElement(metadata, 'Creator')
creator.text = creator_name
created = ET.SubElement(metadata, 'Created')
created.text = generated_on
last_change = ET.SubElement(metadata, 'LastChange')
last_change.text = generated_on
root.append(page.to_xml())
for k, v in _attribs.items():
root.attrib[k] = v
return root
def attach_page_style(self, el):
"""Attach the default page style.
Create an automatic-style that refers to the current style
of this element and that refers to the default page style.
"""
current_style = el.get('text:style-name')
style_name = 'P1003'
el1 = SubElement(
self.automatic_styles, 'style:style', attrib={
'style:name': style_name,
'style:master-page-name': "rststyle-pagedefault",
'style:family': "paragraph",
}, nsdict=SNSD)
if current_style:
el1.set('style:parent-style-name', current_style)
el.set('text:style-name', style_name)
def visit_enumerated_list(self, node):
el1 = self.current_element
if self.blockstyle == self.rststyle('blockquote'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-enumlist'),
})
self.list_style_stack.append(self.rststyle('blockquote-enumitem'))
elif self.blockstyle == self.rststyle('highlights'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-enumlist'),
})
self.list_style_stack.append(self.rststyle('highlights-enumitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-enumlist'),
})
self.list_style_stack.append(self.rststyle('epigraph-enumitem'))
else:
liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), )
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle(liststylename),
})
self.list_style_stack.append(self.rststyle('enumitem'))
self.set_current_element(el2)
def visit_inline(self, node):
styles = node.attributes.get('classes', ())
if styles:
el = self.current_element
for inline_style in styles:
el = SubElement(el, 'text:span',
attrib={'text:style-name':
self.rststyle(inline_style)})
count = len(styles)
else:
# No style was specified so use a default style (old code
# crashed if no style was given)
el = SubElement(self.current_element, 'text:span')
count = 1
self.set_current_element(el)
self.inline_style_count_stack.append(count)
def visit_colspec(self, node):
self.column_count += 1
colspec_name = self.rststyle(
'%s%%d.%%s' % TABLESTYLEPREFIX,
(self.table_count, chr(self.column_count), )
)
colwidth = node['colwidth'] / 12.0
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': colspec_name,
'style:family': 'table-column',
}, nsdict=SNSD)
el1_1 = SubElement(el1, 'style:table-column-properties', attrib={
'style:column-width': '%.4fin' % colwidth
},
nsdict=SNSD)
el2 = self.append_child('table:table-column', attrib={
'table:style-name': colspec_name,
})
self.table_width += colwidth
def generate_admonition(self, node, label, title=None):
if hasattr(self.language, 'labels'):
translated_label = self.language.labels[label]
else:
translated_label = label
el1 = SubElement(self.current_element, 'text:p', attrib={
'text:style-name': self.rststyle(
'admon-%s-hdr', (label, )),
})
if title:
el1.text = title
else:
el1.text = '%s!' % (translated_label.capitalize(), )
s1 = self.rststyle('admon-%s-body', (label, ))
self.paragraph_style_stack.append(s1)
#
# Roles (e.g. subscript, superscript, strong, ...
#
def _serialize_type_structure(self, xmlnode, params, shape, name):
structure_node = ElementTree.SubElement(xmlnode, name)
if 'xmlNamespace' in shape.serialization:
namespace_metadata = shape.serialization['xmlNamespace']
attribute_name = 'xmlns'
if namespace_metadata.get('prefix'):
attribute_name += ':%s' % namespace_metadata['prefix']
structure_node.attrib[attribute_name] = namespace_metadata['uri']
for key, value in params.items():
member_shape = shape.members[key]
member_name = member_shape.serialization.get('name', key)
# We need to special case member shapes that are marked as an
# xmlAttribute. Rather than serializing into an XML child node,
# we instead serialize the shape to an XML attribute of the
# *current* node.
if value is None:
# Don't serialize any param whose value is None.
return
if member_shape.serialization.get('xmlAttribute'):
# xmlAttributes must have a serialization name.
xml_attribute_name = member_shape.serialization['name']
structure_node.attrib[xml_attribute_name] = value
continue
self._serialize(member_shape, value, structure_node, member_name)
def _serialize_type_map(self, xmlnode, params, shape, name):
# Given the ``name`` of MyMap, and input of {"key1": "val1"}
# we serialize this as:
# <MyMap>
# <entry>
# <key>key1</key>
# <value>val1</value>
# </entry>
# </MyMap>
node = ElementTree.SubElement(xmlnode, name)
# TODO: handle flattened maps.
for key, value in params.items():
entry_node = ElementTree.SubElement(node, 'entry')
key_name = self._get_serialized_name(shape.key, default_name='key')
val_name = self._get_serialized_name(shape.value,
default_name='value')
self._serialize(shape.key, key, entry_node, key_name)
self._serialize(shape.value, value, entry_node, val_name)
def addPoint(tree,point,pointtype='c'):
"""Draw a point on the XML tree. A function for testing.
Args:
tree (obj): An XML tree.
newpath (obj): The path to be added.
pointtype (str): The string of point type.
"""
x_str,y_str = str(point[0]),str(point[1])
root = tree.getroot()
for pointaddr in root.iter('{http://www.w3.org/2000/svg}g'):
point = ET.SubElement(pointaddr,'{http://www.w3.org/2000/svg}circle')
# Offer two colour choice
if pointtype == 'c':
point.attrib['style'] = 'fill: #0000ff'
else:
point.attrib['style'] = 'fill: #FF0000'
point.attrib['cx'] = x_str
point.attrib['cy'] = y_str
point.attrib['r'] = '0.5'
point.tail = '\n'
def onFinishBuilding(app, exception):
currentVersion = app.env.config["version"]
if "latest_docs_version" in app.env.config["html_context"].keys():
latestVersion = app.env.config["html_context"]["latest_docs_version"]
else:
latestVersion = "dev"
base_domain = app.env.config["html_context"]["SITEMAP_DOMAIN"]
file_path = "./_build/algolia_index/index.json"
sitemap_path = "./_build/sitemap/sitemap_" + currentVersion + ".xml"
checkDirectory(file_path)
checkDirectory(sitemap_path)
f = open(file_path, 'w+')
root = ET.Element("urlset")
root.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
for link in indexObjs:
url = ET.SubElement(root, "url")
ET.SubElement(url, "loc").text = base_domain + str(currentVersion) + "/" + link["url"]
ET.SubElement(url, "changefreq").text = "daily"
ET.SubElement(url, "priority").text = "1" if ( currentVersion == latestVersion ) else "0.5"
ET.ElementTree(root).write(sitemap_path)
f.write(json.dumps(indexObjs))
def eccu_doc_for_purge_dir(path_to_purge):
root = ET.Element('eccu')
parent = root
names = (name for name in path_to_purge.split('/') if name)
for name in names:
parent = ET.SubElement(parent, 'match:recursive-dirs', {'value': name})
revalidate = ET.SubElement(parent, 'revalidate')
revalidate.text = 'now'
return ET.tostring(root, encoding='ascii') #'<?xml version="1.0"?>\n' + ET.tostring(root)
#xml = StringIO()
#xml.write('<?xml version="1.0"?>\n')
#xml.write(ET.tostring(root))
#return xml
def add_to_document(self, parent):
"""Adds an ``Argument`` object to this ElementTree document.
Adds an <arg> subelement to the parent element, typically <args>
and sets up its subelements with their respective text.
:param parent: An ``ET.Element`` to be the parent of a new <arg> subelement
:returns: An ``ET.Element`` object representing this argument.
"""
arg = ET.SubElement(parent, "arg")
arg.set("name", self.name)
if self.title is not None:
ET.SubElement(arg, "title").text = self.title
if self.description is not None:
ET.SubElement(arg, "description").text = self.description
if self.validation is not None:
ET.SubElement(arg, "validation").text = self.validation
# add all other subelements to this Argument, represented by (tag, text)
subelements = [
("data_type", self.data_type),
("required_on_edit", self.required_on_edit),
("required_on_create", self.required_on_create)
]
for name, value in subelements:
ET.SubElement(arg, name).text = str(value).lower()
return arg