本文整理汇总了Python中xml.etree.cElementTree.tostring方法的典型用法代码示例。如果您正苦于以下问题:Python cElementTree.tostring方法的具体用法?Python cElementTree.tostring怎么用?Python cElementTree.tostring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.cElementTree
的用法示例。
在下文中一共展示了cElementTree.tostring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def save(self, name, settings=None):
writer = GXXmlWriter()
objects = ET.Element("Objects")
for it in self:
node = ET.SubElement(objects, "GXDLMS" + GXDLMSConverter.objectTypeToString(it.objectType))
if it.shortName != 0:
ET.SubElement(node, "SN").text = str(it.shortName)
ET.SubElement(node, "LN").text = it.logicalName
if it.version != 0:
ET.SubElement(node, "Version").text = str(it.version)
if it.description:
ET.SubElement(node, "Description").text = it.description
if not settings or settings.values:
writer.objects = []
writer.objects.append(node)
it.save(writer)
str_ = minidom.parseString(ET.tostring(objects, encoding='utf-8', method='xml')).toprettyxml(indent=" ")
with open(name, "w") as f:
f.write(str_)
示例2: _do_scheme
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def _do_scheme(self):
scheme = Scheme(self.title)
scheme.description = self.description
scheme.use_external_validation = self.use_external_validation
scheme.streaming_mode = Scheme.streaming_mode_xml
scheme.use_single_instance = self.use_single_instance
for argument in self.extra_arguments():
name = argument['name']
title = argument.get('title', None)
description = argument.get('description', None)
validation = argument.get('validation', None)
data_type = argument.get('data_type', Argument.data_type_string)
required_on_edit = argument.get('required_on_edit', False)
required_on_create = argument.get('required_on_create', False)
scheme.add_argument(
Argument(name, title=title, description=description,
validation=validation, data_type=data_type,
required_on_edit=required_on_edit,
required_on_create=required_on_create))
return ET.tostring(scheme.to_xml(), encoding=SCHEME_ENCODING)
示例3: reset_rebuild_data
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def reset_rebuild_data(self, project):
data = self.api.pseudometa_file_load('support_pkg_rebuild')
if data is None:
return
root = ET.fromstring(data)
for stg in root.findall('staging'):
if stg.get('name') == project:
stg.find('rebuild').text = 'unknown'
stg.find('supportpkg').text = ''
# reset accepted staging project rebuild state to unknown and clean up
# supportpkg list
content = ET.tostring(root)
if content != data:
self.api.pseudometa_file_save('support_pkg_rebuild', content, 'accept command update')
示例4: create_bootstrap_aggregate_file
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def create_bootstrap_aggregate_file(self):
url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_aggregate'])
root = ET.Element('aggregatelist')
a = ET.SubElement(root, 'aggregate',
{'project': '{}:0-Bootstrap'.format(self.api.crings)})
for package in self.bootstrap_packages():
p = ET.SubElement(a, 'package')
p.text = package
ET.SubElement(a, 'repository', {'target': 'bootstrap_copy', 'source': 'standard'})
ET.SubElement(a, 'repository', {'target': 'standard', 'source': 'nothing'})
ET.SubElement(a, 'repository', {'target': 'images', 'source': 'nothing'})
self.api.retried_PUT(url, ET.tostring(root))
示例5: add_explicit_disable
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def add_explicit_disable(self, wipebinaries=False):
self._init_biarch_packages()
resulturl = self.makeurl(['source', self.project])
result = ET.fromstring(self.cached_GET(resulturl))
for pkg in self.packages:
changed = False
logger.debug("processing %s", pkg)
if not pkg in self.package_metas:
logger.error("%s not found", pkg)
continue
pkgmeta = self.package_metas[pkg]
build = pkgmeta.findall("./build")
if not build:
logger.debug('disable %s for %s', pkg, self.arch)
bn = pkgmeta.find('build')
if bn is None:
bn = ET.SubElement(pkgmeta, 'build')
ET.SubElement(bn, 'disable', { 'arch': self.arch })
changed = True
if changed:
try:
pkgmetaurl = self.makeurl(['source', self.project, pkg, '_meta'])
self.http_PUT(pkgmetaurl, data=ET.tostring(pkgmeta))
if self.caching:
self._invalidate__cached_GET(pkgmetaurl)
if wipebinaries:
self.http_POST(self.makeurl(['build', self.project], {
'cmd': 'wipe',
'arch': self.arch,
'package': pkg }))
except HTTPError as e:
logger.error('failed to update %s: %s', pkg, e)
示例6: check_diff
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def check_diff(self, package, old_prj, new_prj):
logging.debug('checking %s ...' % package)
query = {'cmd': 'diff',
'view': 'xml',
'oproject': old_prj,
'opackage': package}
u = makeurl(self.apiurl, ['source', new_prj, package], query=query)
root = ET.parse(http_POST(u)).getroot()
old_srcmd5 = root.findall('old')[0].get('srcmd5')
logging.debug('%s old srcmd5 %s in %s' % (package, old_srcmd5, old_prj))
new_srcmd5 = root.findall('new')[0].get('srcmd5')
logging.debug('%s new srcmd5 %s in %s' % (package, new_srcmd5, new_prj))
# Compare srcmd5
if old_srcmd5 != new_srcmd5:
# check if it has diff element
diffs = root.findall('files/file/diff')
if diffs:
return ET.tostring(root)
return False
示例7: freeze
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def freeze(self):
"""Main method"""
flink = ET.Element('frozenlinks')
fl = ET.SubElement(flink, 'frozenlink', {'project': self.factory})
ignored_sources = self.receive_sources(fl)
if self.debug:
logging.debug("Dump ignored source")
for source in ignored_sources:
logging.debug("Ignored source: %s" % source)
url = makeurl(self.apiurl, ['source', FCC, '_project', '_frozenlinks'], {'meta': '1'})
l = ET.tostring(flink)
try:
http_PUT(url, data=l)
except HTTPError as e:
raise e
示例8: send_xml
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def send_xml(self, xml_dict):
data_root = Element('msg')
data_root.set('t', 'sys')
sub_element_parent = data_root
for sub_element, sub_element_attribute in xml_dict.items():
sub_element_object = SubElement(sub_element_parent, sub_element)
if type(xml_dict[sub_element]) is dict:
for sub_element_attribute_key, sub_element_attribute_value in xml_dict[sub_element].items():
sub_element_object.set(sub_element_attribute_key, sub_element_attribute_value)
else:
sub_element_object.text = xml_dict[sub_element]
sub_element_parent = sub_element_object
xml_data = tostring(data_root)
await self.send_line(xml_data.decode('utf-8'))
示例9: __init__
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def __init__(self, filename):
# TODO: remove this when upstream fixes translations with Python3+Windows
if sys.platform == "win32" and not conf.no_gettext:
tree = ET.parse(addDataPrefix("glade/%s" % filename))
for node in tree.iter():
if 'translatable' in node.attrib:
node.text = _(node.text)
del node.attrib['translatable']
if node.get('name') in ('pixbuf', 'logo'):
node.text = addDataPrefix("glade/%s" % node.text)
xml_text = ET.tostring(tree.getroot(), encoding='unicode', method='xml')
self.builder = Gtk.Builder.new_from_string(xml_text, -1)
else:
self.builder = Gtk.Builder()
if not conf.no_gettext:
self.builder.set_translation_domain("pychess")
self.builder.add_from_file(addDataPrefix("glade/%s" % filename))
示例10: export_reddit_objects_to_xml
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def export_reddit_objects_to_xml(object_list, file_path):
"""
Exports the supplied list of RedditObjects to an xml format with each xml element representing one reddit object
with all of its relevant and formattable attributes. Some attributes are omitted from export either due to the
resulting file size or irrelevancy.
:param object_list: A list of RedditObjects which are to be exported to an xml file.
:param file_path: The path at which the xml file will be created.
"""
root = et.Element('reddit_objects')
user_root = et.SubElement(root, 'users')
subreddit_root = et.SubElement(root, 'subreddits')
for ro in object_list:
if ro.object_type == 'USER':
make_reddit_object_element(user_root, ro)
else:
make_reddit_object_element(subreddit_root, ro)
xml = minidom.parseString(et.tostring(root)).toprettyxml(indent=' ')
with open(file_path, mode='a', encoding='utf-8') as file:
file.write(xml)
logger.info('Exported reddit object list to xml file', extra={'export_count': len(object_list)})
示例11: send_feedback
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
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
####################################################################
示例12: __repr__
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def __repr__(self):
s = ElementTree.tostring(self._etree, encoding='utf8').decode('utf8')
if len(s) > 60:
e = s.rfind('<')
if (len(s)-e) > 30: e = -20
s = '%s...%s' % (s[:30], s[e:])
return '<Element %r>' % s
示例13: __str__
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
def __str__(self):
"""
:return: the result of applying ``ElementTree.tostring()`` to
the wrapped Element object.
"""
return ElementTree.tostring(self._etree, encoding='utf8').decode('utf8').rstrip()
##////////////////////////////////////////////////////////////
#{ Element interface Delegation (pass-through)
##////////////////////////////////////////////////////////////
示例14: write_to
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
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")
if isinstance(stream, TextIOBase):
stream.write(ensure_text(ET.tostring(event)))
else:
stream.write(ET.tostring(event))
stream.flush()
示例15: write_to
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import tostring [as 别名]
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).decode())
stream.flush()