Python xml.etree.ElementTree 模块,tostring() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xml.etree.ElementTree.tostring()。
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})
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
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)
def makeBody(self, attrs, child, status):
body = ET.Element("subsonic-response")
attrs_ = {"status": "ok" if status is True else "failed",
"xmlns": "http://subsonic.org/restapi",
"version": PROTOCOL_VERSION,
"unsonic": UNSONIC_PROTOCOL_VERSION}
attrs_.update(attrs)
for key, value in attrs_.items():
body.set(key, value)
if status is not True and status is not False:
error = ET.Element("error")
if isinstance(status[0], tuple):
error.set("code", status[0][0])
error.set("message", "%s: %s" % (status[0][1], status[1]))
else:
error.set("code", status[0])
error.set("message", status[1])
body.append(error)
if child is not None:
body.append(child)
return "%s%s\n" % (XML_HEADER, ET.tostring(body).decode("utf-8"))
def parseliteral():
"""
>>> element = ET.XML("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
<html><body>text</body></html>
>>> element = ET.fromstring("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
<html><body>text</body></html>
>>> sequence = ["<html><body>", "text</bo", "dy></html>"]
>>> element = ET.fromstringlist(sequence)
>>> ET.tostring(element)
b'<html><body>text</body></html>'
>>> b"".join(ET.tostringlist(element))
b'<html><body>text</body></html>'
>>> ET.tostring(element, "ascii")
b"<?xml version='1.0' encoding='ascii'?>\\n<html><body>text</body></html>"
>>> _, ids = ET.XMLID("<html><body>text</body></html>")
>>> len(ids)
0
>>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>")
>>> len(ids)
1
>>> ids["body"].tag
'body'
"""
def processinginstruction():
"""
Test ProcessingInstruction directly
>>> ET.tostring(ET.ProcessingInstruction('test', 'instruction'))
b'<?test instruction?>'
>>> ET.tostring(ET.PI('test', 'instruction'))
b'<?test instruction?>'
Issue #2746
>>> ET.tostring(ET.PI('test', '<testing&>'))
b'<?test <testing&>?>'
>>> ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin1')
b"<?xml version='1.0' encoding='latin1'?>\\n<?test <testing&>\\xe3?>"
"""
#
# xinclude tests (samples from appendix C of the xinclude specification)
def _extarct_only_robot(xmlfile):
"""remove from file not robot's elements
robot elements are: 'suite' 'statistics' 'errors'
"""
original_doc = ET.parse(xmlfile)
root = original_doc.getroot()
devices = root.find("devices")
if devices is not None:
root.remove(devices)
source = StringIO(ET.tostring(root))
ets = ETSource(source)
execution_result = ExecutionResultBuilder(ets).build(Result())
patched_file = File(BytesIO(force_bytes(source.getvalue())), name=xmlfile.name)
return (execution_result, patched_file)
def send_feedback(self):
"""Print stored items to console/Alfred as XML."""
root = ET.Element('items')
for item in self._items:
root.append(item.elem)
sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n')
sys.stdout.write(ET.tostring(root).encode('utf-8'))
sys.stdout.flush()
####################################################################
# Updating methods
####################################################################
def build_soap_xml(items, namespace=None):
"""Build a SOAP XML.
:param items: a list of dictionaries where key is the element name
and the value is the element text.
:param namespace: the namespace for the elements, None for no
namespace. Defaults to None
:returns: a XML string.
"""
def _create_element(name, value=None):
xml_string = name
if namespace:
xml_string = "{%(namespace)s}%(item)s" % {'namespace': namespace,
'item': xml_string}
element = ElementTree.Element(xml_string)
element.text = value
return element
soap_namespace = "http://www.w3.org/2003/05/soap-envelope"
envelope_element = ElementTree.Element("{%s}Envelope" % soap_namespace)
body_element = ElementTree.Element("{%s}Body" % soap_namespace)
for item in items:
for i in item:
insertion_point = _create_element(i)
if isinstance(item[i], dict):
for j, value in item[i].items():
insertion_point.append(_create_element(j, value))
else:
insertion_point.text = item[i]
body_element.append(insertion_point)
envelope_element.append(body_element)
return ElementTree.tostring(envelope_element)
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 write_to(self, stream):
"""Write an XML representation of self, an ``Event`` object, to the given stream.
The ``Event`` object will only be written if its data field is defined,
otherwise a ``ValueError`` is raised.
:param stream: stream to write XML to.
"""
if self.data is None:
raise ValueError("Events must have at least the data field set to be written to XML.")
event = ET.Element("event")
if self.stanza is not None:
event.set("stanza", self.stanza)
event.set("unbroken", str(int(self.unbroken)))
# if a time isn't set, let Splunk guess by not creating a <time> element
if self.time is not None:
ET.SubElement(event, "time").text = str(self.time)
# add all other subelements to this Event, represented by (tag, text)
subelements = [
("source", self.source),
("sourcetype", self.sourceType),
("index", self.index),
("host", self.host),
("data", self.data)
]
for node, value in subelements:
if value is not None:
ET.SubElement(event, node).text = value
if self.done:
ET.SubElement(event, "done")
stream.write(ET.tostring(event))
stream.flush()
def send_feedback(self):
"""Print stored items to console/Alfred as XML."""
root = ET.Element('items')
for item in self._items:
root.append(item.elem)
sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n')
sys.stdout.write(ET.tostring(root).encode('utf-8'))
sys.stdout.flush()
####################################################################
# Updating methods
####################################################################
def send_feedback(self):
"""Print stored items to console/Alfred as XML."""
root = ET.Element('items')
for item in self._items:
root.append(item.elem)
sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n')
sys.stdout.write(ET.tostring(root).encode('utf-8'))
sys.stdout.flush()
####################################################################
# Updating methods
####################################################################
def build_body_html(xml):
elements = []
for elem in xml.find('body/body.content'):
if elem.tag == 'p' and elem.get('class') == 'lead':
continue
elements.append(ET.tostring(elem, encoding='unicode'))
return ''.join(elements)
def set_boot_device(self, bootdevice):
LOG.debug('Set boot device called for %(domain)s with boot '
'device "%(bootdev)s"', {'domain': self.domain_name,
'bootdev': bootdevice})
device = SET_BOOT_DEVICES_MAP.get(bootdevice)
if device is None:
return 0xd5
with utils.libvirt_open(**self._conn_args) as conn:
domain = utils.get_libvirt_domain(conn, self.domain_name)
tree = ET.fromstring(domain.XMLDesc())
for os_element in tree.findall('os'):
# Remove all "boot" elements
for boot_element in os_element.findall('boot'):
os_element.remove(boot_element)
# Add a new boot element with the request boot device
boot_element = ET.SubElement(os_element, 'boot')
boot_element.set('dev', device)
try:
conn.defineXML(ET.tostring(tree))
except libvirt.libvirtError as e:
LOG.error('Failed setting the boot device %(bootdev)s for '
'domain %(domain)s', {'bootdev': device,
'domain': self.domain_name})
def __write(self):
h = open(self.out, 'w')
h.write("import xml.etree.ElementTree as ET\n\n")
# prints namespace constants
h.writelines(["%s = '%s'\n" % (v, k) for k, v in self.constants.items()])
h.write("\n")
h.write("def build(**kwargs):\n\t")
h.write("\n\t".join(self.lines))
h.write("\n\treturn ET.tostring(%s)\n\n" % self.root)
h.write("if __name__ == '__main__': print build()")
h.close()
def write_to(self, stream):
"""Write an XML representation of self, an ``Event`` object, to the given stream.
The ``Event`` object will only be written if its data field is defined,
otherwise a ``ValueError`` is raised.
:param stream: stream to write XML to.
"""
if self.data is None:
raise ValueError("Events must have at least the data field set to be written to XML.")
event = ET.Element("event")
if self.stanza is not None:
event.set("stanza", self.stanza)
event.set("unbroken", str(int(self.unbroken)))
# if a time isn't set, let Splunk guess by not creating a <time> element
if self.time is not None:
ET.SubElement(event, "time").text = str(self.time)
# add all other subelements to this Event, represented by (tag, text)
subelements = [
("source", self.source),
("sourcetype", self.sourceType),
("index", self.index),
("host", self.host),
("data", self.data)
]
for node, value in subelements:
if value is not None:
ET.SubElement(event, node).text = value
if self.done:
ET.SubElement(event, "done")
stream.write(ET.tostring(event))
stream.flush()
def _save_xml_report(self, s):
'''use cppcheck xml result string, add the command string used to invoke cppcheck
and save as xml file.
'''
header = '%s\n' % s.splitlines()[0]
root = ElementTree.fromstring(s)
cmd = ElementTree.SubElement(root.find('cppcheck'), 'cmd')
cmd.text = str(self.cmd)
body = ElementTree.tostring(root)
node = self.generator.path.get_bld().find_or_declare('cppcheck.xml')
node.write(header + body)
def _create_html_file(self, sourcefile, htmlfile, errors):
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
srcnode = self.generator.bld.root.find_node(sourcefile)
hl_lines = [e['line'] for e in errors if e.has_key('line')]
formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
formatter.errors = [e for e in errors if e.has_key('line')]
css_style_defs = formatter.get_style_defs('.highlight')
lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
s = pygments.highlight(srcnode.read(), lexer, formatter)
table = ElementTree.fromstring(s)
content.append(table)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare(htmlfile)
node.write(s)
return css_style_defs
def _save_xml_report(self, s):
'''use cppcheck xml result string, add the command string used to invoke cppcheck
and save as xml file.
'''
header = '%s\n' % s.splitlines()[0]
root = ElementTree.fromstring(s)
cmd = ElementTree.SubElement(root.find('cppcheck'), 'cmd')
cmd.text = str(self.cmd)
body = ElementTree.tostring(root)
node = self.generator.path.get_bld().find_or_declare('cppcheck.xml')
node.write(header + body)
def _create_html_file(self, sourcefile, htmlfile, errors):
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
srcnode = self.generator.bld.root.find_node(sourcefile)
hl_lines = [e['line'] for e in errors if e.has_key('line')]
formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
formatter.errors = [e for e in errors if e.has_key('line')]
css_style_defs = formatter.get_style_defs('.highlight')
lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
s = pygments.highlight(srcnode.read(), lexer, formatter)
table = ElementTree.fromstring(s)
content.append(table)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare(htmlfile)
node.write(s)
return css_style_defs
def _save_xml_report(self, s):
'''use cppcheck xml result string, add the command string used to invoke cppcheck
and save as xml file.
'''
header = '%s\n' % s.splitlines()[0]
root = ElementTree.fromstring(s)
cmd = ElementTree.SubElement(root.find('cppcheck'), 'cmd')
cmd.text = str(self.cmd)
body = ElementTree.tostring(root)
node = self.generator.path.get_bld().find_or_declare('cppcheck.xml')
node.write(header + body)
def _create_html_file(self, sourcefile, htmlfile, errors):
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
srcnode = self.generator.bld.root.find_node(sourcefile)
hl_lines = [e['line'] for e in errors if e.has_key('line')]
formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
formatter.errors = [e for e in errors if e.has_key('line')]
css_style_defs = formatter.get_style_defs('.highlight')
lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
s = pygments.highlight(srcnode.read(), lexer, formatter)
table = ElementTree.fromstring(s)
content.append(table)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare(htmlfile)
node.write(s)
return css_style_defs