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类tostring()的实例源码
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)
def checkCobertura(config, checkoutSteps, buildSteps, packageSteps, **kwargs):
found = False
for s in checkoutSteps:
if s.getPackage().getName().endswith("unittests"): found = True
for s in buildSteps:
if s.getPackage().getName().endswith("unittests"): found = True
for s in packageSteps:
if s.getPackage().getName().endswith("unittests"): found = True
if found:
root = ElementTree.fromstring(config)
publishers = root.find("publishers")
if publishers.find("hudson.plugins.cobertura.CoberturaPublisher") is None:
publishers.append(PLUGIN)
config = ElementTree.tostring(root, encoding="UTF-8")
return config
parameterwidgets.py 文件源码
项目:SLP-Annotator
作者: PhonologicalCorpusTools
项目源码
文件源码
阅读 64
收藏 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 _create_html_index(self, files):
name = self.generator.get_name()
root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
title = root.find('head/title')
title.text = 'cppcheck - report - %s' % name
body = root.find('body')
for div in body.findall('div'):
if div.get('id') == 'page':
page = div
break
for div in page.findall('div'):
if div.get('id') == 'header':
h1 = div.find('h1')
h1.text = 'cppcheck report - %s' % name
if div.get('id') == 'content':
content = div
self._create_html_table(content, files)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare('cppcheck/index.html')
node.write(s)
return node
def _create_html_index(self, files):
name = self.generator.get_name()
root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
title = root.find('head/title')
title.text = 'cppcheck - report - %s' % name
body = root.find('body')
for div in body.findall('div'):
if div.get('id') == 'page':
page = div
break
for div in page.findall('div'):
if div.get('id') == 'header':
h1 = div.find('h1')
h1.text = 'cppcheck report - %s' % name
if div.get('id') == 'content':
content = div
self._create_html_table(content, files)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare('cppcheck/index.html')
node.write(s)
return node
def assert_case(case_name):
case_source, case_result = (os.path.join(BASE_PATH, case_name + ext) for ext in ['.yml', '.xml'])
jjb_config = JJBConfig()
builder = Builder(jjb_config)
# Generate XML
parser = YamlParser(jjb_config)
registry = ModuleRegistry(jjb_config, builder.plugins_list)
xml_generator = XmlJobGenerator(registry)
parser.load_files(case_source)
registry.set_parser_data(parser.data)
job_data_list = parser.expandYaml(registry, [])
xml_jobs = xml_generator.generateXML(job_data_list)
result_xml = ET.XML(xml_jobs[0].output())
expected_xml = ET.XML(open(case_result).read())
assert ET.tostring(result_xml) == ET.tostring(expected_xml)
def get_xml(self, encoding='utf-8'):
"""
Returns the XML-code of this schedule.
The returned byte string contains the XML in the requested encoding. You save the byte sting to file in binary
mode (the file will encoded the requested encoding). Or you can convert the byte string to a string with
.decode(encoding).
:param str encoding: The encoding of the XML.
:rtype: bytes
"""
tree = Element(None)
self.generate_xml(tree)
xml_string = ElementTree.tostring(tree)
document = minidom.parseString(xml_string)
return document.toprettyxml(indent=' ', encoding=encoding)
# ------------------------------------------------------------------------------------------------------------------
def passage2file(passage, filename, indent=True, binary=False):
"""Writes a UCCA passage as a standard XML file or a binary pickle
:param passage: passage object to write
:param filename: file name to write to
:param indent: whether to indent each line
:param binary: whether to write pickle format (or XML)
"""
if binary:
with open(filename, "wb") as h:
pickle.dump(passage, h)
else: # xml
root = to_standard(passage)
xml = ET.tostring(root).decode()
output = textutil.indent_xml(xml) if indent else xml
with open(filename, "w", encoding="utf-8") as h:
h.write(output)
def __SendDataPart(data, connection):
"""This method is deprecated, use atom.http._send_data_part"""
deprecated('call to deprecated function __SendDataPart')
if isinstance(data, str):
#TODO add handling for unicode.
connection.send(data)
return
elif ElementTree.iselement(data):
connection.send(ElementTree.tostring(data))
return
# Check to see if data is a file-like object that has a read method.
elif hasattr(data, 'read'):
# Read the file and send it a chunk at a time.
while 1:
binarydata = data.read(100000)
if binarydata == '': break
connection.send(binarydata)
return
else:
# The data object was not a file.
# Try to convert to a string and send the data.
connection.send(str(data))
return
def CalculateDataLength(data):
"""Attempts to determine the length of the data to send.
This method will respond with a length only if the data is a string or
and ElementTree element.
Args:
data: object If this is not a string or ElementTree element this funtion
will return None.
"""
if isinstance(data, str):
return len(data)
elif isinstance(data, list):
return None
elif ElementTree.iselement(data):
return len(ElementTree.tostring(data))
elif hasattr(data, 'read'):
# If this is a file-like object, don't try to guess the length.
return None
else:
return len(str(data))
def test_to_xml(self):
random_cbid = random_string(random.randint(8, 24))
random_actions = [Decl('a', Value([Data("abcdef")])),
Delay(random.randint(0, 10000))]
# create XML representation by hand
element = Element('pov')
cbid = Element('cbid')
cbid.text = random_cbid
element.append(cbid)
replay = Element('replay')
for action in random_actions:
replay.append(action.to_xml())
element.append(replay)
# create POV and XML representation automatically
pov = CQE_POV(random_cbid, random_actions)
self.assertTrue(repr(pov) == ElementTree.tostring(element))
def etree_tostring(elem, indent='', max_lines=None, spaces_for_tab=4):
if PY3:
lines = ElementTree.tostring(elem, encoding="unicode").splitlines()
else:
# noinspection PyCompatibility
lines = unicode(ElementTree.tostring(elem)).splitlines()
while lines and not lines[-1].strip():
lines.pop(-1)
lines[-1] = ' %s' % lines[-1].strip()
if max_lines is not None:
if indent:
xml_text = '\n'.join([indent + line for line in lines[:max_lines]])
else:
xml_text = '\n'.join(lines[:max_lines])
if len(lines) > max_lines + 2:
xml_text += '\n%s ...\n%s%s' % (indent, indent, lines[-1])
elif len(lines) > max_lines:
xml_text += '\n%s%s\n%s%s' % (indent, lines[-2], indent, lines[-1])
elif indent:
xml_text = '\n'.join([indent + line for line in lines])
else:
xml_text = '\n'.join(lines)
return xml_text.replace('\t', ' ' * spaces_for_tab) if spaces_for_tab else xml_text
def save(self):
root = ET.Element('TS')
if self.version:
root.attrib['version'] = self.version
if self.language:
root.attrib['language'] = self.language
for ctx in sorted(self.__contexts.itervalues()):
ctx.save(root)
rough_string = ET.tostring(root, 'utf-8')
reparsed = minidom.parseString(rough_string)
text = reparsed.toprettyxml(indent=" ")
text = text.encode('utf-8')
with open(self.__file, 'wb') as f:
f.write(text)
def update_memory(self, name, memory):
conn = self.conn
memory = str(int(memory) * 1024)
try:
vm = conn.lookupByName(name)
xml = vm.XMLDesc(0)
root = ET.fromstring(xml)
except:
print("VM %s not found" % name)
return {'result': 'failure', 'reason': "VM %s not found" % name}
memorynode = root.getiterator('memory')[0]
memorynode.text = memory
currentmemory = root.getiterator('currentMemory')[0]
currentmemory.text = memory
newxml = ET.tostring(root)
conn.defineXML(newxml)
return {'result': 'success'}
def remove_cloudinit(self, name):
conn = self.conn
try:
vm = conn.lookupByName(name)
xml = vm.XMLDesc(0)
root = ET.fromstring(xml)
except:
print("VM %s not found" % name)
return {'result': 'failure', 'reason': "VM %s not found" % name}
for element in root.getiterator('disk'):
disktype = element.get('device')
if disktype == 'cdrom':
source = element.find('source')
path = source.get('file')
if source is None:
break
volume = conn.storageVolLookupByPath(path)
volume.delete(0)
element.remove(source)
newxml = ET.tostring(root)
conn.defineXML(newxml)
def __init__(self, e, files):
# Every step requires a name.
if 'name' not in e.attrib or len(e.attrib) != 1:
msg = ("Step must have (only) a name attribute. Tag had these "
"attributes: '{}'\n{}".format(", ".join(e.attrib.keys()), ET.tostring(e)))
raise ParseError(msg)
self.name = e.attrib['name'].replace(' ', '_')
self.tools = []
self.code = "S"
for child in e:
t = child.tag
if t not in Step.validTags:
msg = ("Illegal tag in step '{}': \n\n"
"{}\n\nValid Tags: '{}'".format(self.name,
ET.tostring(child).rstrip(),
", ".join(Step.validTags)))
raise ParseError(msg)
self.tools.append(PipelineTool(child, files, e.attrib['name']))
def __init__(self, e, pipeline_files):
atts = e.attrib
for a in atts:
if a not in ForEachFile.requiredAtts:
msg = ("Unknown attribute in foreach file: {}\n\n"
"{}\n\nValid Attributes: '{}'".format(a, ET.tostring(e).rstrip(),
", ".join(ForEachFile.requiredAtts)))
raise ParseError(msg)
for a in ForEachFile.requiredAtts:
if a not in atts:
msg = ("foreach file tag missing required attribute:\n\n{}\n\n"
"Required Attributes: '{}'".format(ET.tostring(e).rstrip(),
", ".join(ForEachFile.requiredAtts)))
raise ParseError(msg)
self.id = atts['id']
if self.id in pipeline_files:
msg = "a foreach file's id must not be the same as a pipeline file id: {}\n\n{}".format(self.id, ET.tostring(e))
raise ParseError(msg)
self.pattern = re.compile(atts['pattern'])
def write(self, filename):
xml = ET.Element("phonebooks")
for book in self.phonebookList:
xml.append(book.getXML())
tree = ET.ElementTree(xml)
if False:
tree.write(filename, encoding="iso-8859-1", xml_declaration=True)
else:
rough_string = ET.tostring(tree.getroot(), encoding="iso-8859-1", method="xml")
reparsed = parseString(rough_string)
pretty = reparsed.toprettyxml(indent=" ", encoding="iso-8859-1").decode("iso-8859-1")
with open(filename, 'w', encoding="iso-8859-1") as outfile:
outfile.write(pretty)
# sid: Login session ID
# phonebookid: 0 for main phone book
# 1 for next phone book in list, etc...
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 getConfigElementTextWithSpecificXpath(datafile, xpath):
"""
This method takes an xml document as input and finds the first sub element (parent/children)
containing specified xpath which should be a filepath to a netconf config file
Returns the element text attribute
Arguments:
parent = parent element
xpath = a valid xml path value as supported by python, refer https://docs.python.org/2/library/xml.etree.elementtree.html
"""
root = ElementTree.parse(datafile).getroot()
elem1 = root.find(xpath).text
elem2_root = ElementTree.parse(elem1)
elem2 = elem2_root.find('config')
elem2_string = ElementTree.tostring(elem2)
return elem2_string
def mountIso(self,instance,dev, image):
tree = ElementTree.fromstring(self.getInsXMLDesc(instance,0))
for disk in tree.findall('devices/disk'):
if disk.get('device') == 'cdrom':
for elm in disk:
if elm.tag == 'target':
if elm.get('dev') == dev:
src_media = ElementTree.Element('source')
src_media.set('file', image)
disk.append(src_media)
if instance.state()[0] == 1:
xml_disk = ElementTree.tostring(disk)
try:
instance.attachDevice(xml_disk)
except libvirt.libvirtError,e:
return '??????????{result}'.format(result=e.get_error_message())
xmldom = self.getInsXMLDesc(instance,1)
if instance.state()[0] == 5:
xmldom = ElementTree.tostring(tree)
try:
return self.defineXML(xmldom)
except libvirt.libvirtError,e:
return '??????????{result}'.format(result=e.get_error_message())
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 process_scaling(ui_content: str, ratio: float) -> str:
tree = ElementTree.fromstring(ui_content)
for child in tree.iter('width'):
if child.text != '16777215':
child.text = str(int(int(child.text) * ratio))
for child in tree.iter('height'):
if child.text != '16777215':
child.text = str(int(int(child.text) * ratio))
for child in tree.iter("property"):
name = child.attrib.get('name', None)
if name == 'spacing' or name[-6:] == 'Margin' and len(child):
number = child[0]
number.text = str(int(int(number.text) * ratio))
ui_content = ElementTree.tostring(tree, encoding='unicode')
ui_content = ui_content.replace(' />\n', '/>\n')
return '<?xml version="1.0" encoding="UTF-8"?>\n' + ui_content + '\n'
def query(self, cmd, state, *args, **kwargs):
"""Create an XML string for the 'interp' command."""
# Attrs:
# raw - ?
# bool - Verbose output
# int - The current state id
# Args:
# string - The query to evaluate
elt = ET.Element('call', {'val': 'interp',
'raw': 'true',
'verbose': 'true',
'id': str(state)})
elt.text = cmd
return ('Query',
ET.tostring(elt,
kwargs.get('encoding', 'utf-8')))
def gen_xml(rowList):
items = Element('items')
for row in rowList:
item = SubElement(items, 'item')
item.set('autocomplete', row.get('autocomplete') or '')
item.set('uid', row.get('uid') or '')
item.set('arg', row.get('title') or '')
item.set('valid', row.get('valid') or '')
title = SubElement(item, 'title')
title.text = row.get('title') or ''
subtitle = SubElement(item, 'subtitle')
subtitle.text = row.get('subtitle') or ''
icon = SubElement(item, 'icon')
icon.text = row.get('icon')
tree = minidom.parseString(etree.tostring(items))
return tree.toxml()
def rpc_create_subscription(self, unused_session, rpc, *unused_params):
logger.info("rpc_create-subscription")
logger.debug("Session:%s", format(unused_session))
logger.debug("RPC received:%s", format(etree.tostring(rpc)))
for param in unused_params:
logger.debug("Param:" + etree.tostring(param))
unused_session.subscription_active = True
return etree.Element("ok")
# **********************************
# Setup SNMP
# **********************************
def make_tag_request(**kwargs):
NS = "http://musicbrainz.org/ns/mmd-2.0#"
root = ET.Element("{%s}metadata" % NS)
for entity_type in ['artist', 'label', 'place', 'recording', 'release', 'release_group', 'work']:
entity_tags = kwargs.pop(entity_type + '_tags', None)
if entity_tags is not None:
e_list = ET.SubElement(root, "{%s}%s-list" % (NS, entity_type.replace('_', '-')))
for e, tags in entity_tags.items():
e_xml = ET.SubElement(e_list, "{%s}%s" % (NS, entity_type.replace('_', '-')))
e_xml.set("{%s}id" % NS, e)
taglist = ET.SubElement(e_xml, "{%s}user-tag-list" % NS)
for tag in tags:
usertag_xml = ET.SubElement(taglist, "{%s}user-tag" % NS)
name_xml = ET.SubElement(usertag_xml, "{%s}name" % NS)
name_xml.text = tag
if kwargs.keys():
raise TypeError("make_tag_request() got an unexpected keyword argument '%s'" % kwargs.popitem()[0])
return ET.tostring(root, "utf-8")
def make_rating_request(**kwargs):
NS = "http://musicbrainz.org/ns/mmd-2.0#"
root = ET.Element("{%s}metadata" % NS)
for entity_type in ['artist', 'label', 'recording', 'release_group', 'work']:
entity_ratings = kwargs.pop(entity_type + '_ratings', None)
if entity_ratings is not None:
e_list = ET.SubElement(root, "{%s}%s-list" % (NS, entity_type.replace('_', '-')))
for e, rating in entity_ratings.items():
e_xml = ET.SubElement(e_list, "{%s}%s" % (NS, entity_type.replace('_', '-')))
e_xml.set("{%s}id" % NS, e)
rating_xml = ET.SubElement(e_xml, "{%s}user-rating" % NS)
rating_xml.text = str(rating)
if kwargs.keys():
raise TypeError("make_rating_request() got an unexpected keyword argument '%s'" % kwargs.popitem()[0])
return ET.tostring(root, "utf-8")
def table_of_contents(self, filepath='', filenumber=1):
if len(self.header_list) < 1:
return ''
toc = [('\n<ol class="slidoc-section-toc">' if 'sections' in self.options['config'].strip
else '\n<ul class="slidoc-section-toc" style="list-style-type: none;">') ]
for id_str, header in self.header_list: # Skip first header
if filepath or self.options['config'].printable:
elem = ElementTree.Element("a", {"class" : "header-link", "href" : filepath+"#"+id_str})
else:
elem = ElementTree.Element("span", {"class" : "slidoc-clickable", "onclick" : "Slidoc.go('#%s');" % id_str})
elem.text = header
toc.append('<li>'+ElementTree.tostring(elem)+'</li>')
toc.append('</ol>\n' if 'sections' in self.options['config'].strip else '</ul>\n')
return '\n'.join(toc)