本文整理汇总了Python中xml.etree.ElementTree.tostringlist方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.tostringlist方法的具体用法?Python ElementTree.tostringlist怎么用?Python ElementTree.tostringlist使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.tostringlist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _diff_configs
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def _diff_configs(remote_config, new_config):
remote_root = ElementTree.fromstring(remote_config)
new_root = ElementTree.fromstring(new_config)
# ignore description which contains timestamp
remote_root.find('description').text = ''
new_root.find('description').text = ''
if ElementTree.tostring(remote_root) == ElementTree.tostring(new_root):
return []
lines1 = ElementTree.tostringlist(remote_root, encoding='unicode')
lines2 = ElementTree.tostringlist(new_root, encoding='unicode')
return difflib.unified_diff(
lines1, lines2, 'remote config', 'new config', n=0)
示例2: etd
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def etd(self):
""" Given origin and direction, list train departure times. """
root = get_xml_tree_from_url(self.url)
try:
time = root.find("time").text
except AttributeError:
msg = "\n".join(ET.tostringlist(root, method="text"))
raise Exception(msg)
station = root.find("station/name").text
print("{} at {}".format(station, time))
for etd in root.findall("station/etd"):
dest = etd.find("destination").text.replace(" ", "")
for estimate in etd.findall("estimate"):
minutes = estimate.find("minutes").text
length = estimate.find("length").text
if minutes.lower() == "leaving":
minute_str = "now leaving"
depart_at = "--:--"
else:
minute_str = "in {:>2} minutes".format(minutes)
if minutes.strip() == "1":
minute_str = minute_str[:-1]
departure = datetime.strptime(time, "%H:%M:%S %p %Z")\
+ timedelta(minutes=int(minutes))
depart_at = datetime.strftime(departure, "%H:%M")
print("\t[{}] {:>2} car {} train {},"\
.format(depart_at, length, dest, minute_str))
示例3: generate_tag
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def generate_tag(tag, content, attributes=None):
"""Generate a complete html tag using the ElementTree module. tag and
content are strings, the attributes argument is a dictionary. As
a convenience, if the content is ' /', a self-closing tag is generated."""
content = six.text_type(content)
enc = 'unicode'
if six.PY2:
enc = 'UTF-8'
if not tag:
return content
element = ElementTree.Element(tag, attrib=attributes)
# FIXME: Kind of an ugly hack. There *must* be a cleaner way. I tried
# adding text by assigning it to element_tag.text. That results in
# non-ascii text being html-entity encoded. Not bad, but not entirely
# matching php-textile either.
try:
element_tag = ElementTree.tostringlist(element, encoding=enc,
method='html')
element_tag.insert(len(element_tag) - 1, content)
element_text = ''.join(element_tag)
except AttributeError:
# Python 2.6 doesn't have the tostringlist method, so we have to treat
# it differently.
element_tag = ElementTree.tostring(element, encoding=enc)
element_text = re.sub(r"<\?xml version='1.0' encoding='UTF-8'\?>\n",
'', element_tag)
if content != six.text_type(' /'):
element_text = element_text.rstrip(' />')
element_text = six.text_type('{0}>{1}</{2}>').format(six.text_type(
element_text), content, tag)
return element_text
示例4: _write_tree
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def _write_tree(self, tree, begin=None, end=None, indent=0):
"""
Write a part of the tree stringlist.
Begin and end are strings that mark begin and end of the part of
the tree that needs to be written. May not work if elementtrees
splitting behaviour gets really weird.
"""
self.xml_output_file.write(indent * ' ')
write = True if begin is None else False
for text in ElementTree.tostringlist(tree):
if begin is not None and begin in text:
write = True
if write:
self.xml_output_file.write(text)
if end is not None and end in text:
break
if (not text.endswith('\n')) and (end is not None):
self.xml_output_file.write('\n')
示例5: tostringlist
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def tostringlist(element, encoding=None, method=None):
"""
@summary: ElementTree.tostringlist wrapper that converts an Element tree
into a pretty printed list of strings
@see: ElementTree.tostring
"""
_prettyFormat(element, level=0)
return ET.tostringlist(element, encoding=encoding, method=method)
示例6: makePackageDict
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def makePackageDict(dir_path, Repos_dict):
package_dict = {}
komodo_dict = komodo.makeDataList('./komodo')
# Parse the files one by one
for f in makeManifestFileList(dir_path):
with open(f, 'r') as open_file:
tree = ET.parse(open_file)
root = tree.getroot()
name = root.find('name').text
repo = Repos_dict[f[f.rindex('/')+1:f.rindex('-')]]
package = Package(name, repo)
for person in extractPeople(root, 'author'):
package.authors.add(person)
for person in extractPeople(root, 'maintainer'):
package.maintainers.add(person)
if '<metapackage' in ET.tostringlist(root):
package.isMetapackage = True
# print " Found metapackage", name
predescription = extractTag(root, 'description')[0].strip().replace('\n','').replace('\r','').replace('\t','').replace('"','').replace(' ','')
package.description = re.sub(r'<.+?>', '', predescription)
package.licenses = set(extractTag(root, 'license'))
prewiki = extractTag(root, 'url')
if prewiki != None and None not in prewiki: prewiki = [url for url in prewiki if 'wiki'in url and 'git' not in url]
if len(prewiki) > 0: package.wiki = prewiki[0]
package.buildtool_depend = set(extractTag(root, 'buildtool_depend'))
package.build_depend = set(extractTag(root, 'build_depend'))
package.run_depend = set(extractTag(root, 'run_depend'))
if (package.name in komodo_dict):
package.runtime = komodo_dict[package.name]
package_dict[package.name] = package
# Calculate reverse dependencies for each package
# Although most are listed under the depends_on key there are pkgs missed
print " Verifying dependencies:",
counts = [0,0]
for p in package_dict.values():
deps = [p.buildtool_depend, p.build_depend, p.run_depend]
for dep in deps:
clone_depend = dep.copy() # Clone these deps to remove invalids when looping
for d in clone_depend:
if d not in package_dict:
dep.remove(d) # Remove deps that are not known packages
counts[0] += 1
else: counts[1] += 1
print " Invalid ", counts[0],
print " Valid ", counts[1]
return package_dict
示例7: _serialize_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def _serialize_xml(self, root):
"""It serializes the dynamic xml created and converts
it to a string. This is done before sending the
xml to the ILO.
:param root: root of the dynamic xml.
"""
if hasattr(etree, 'tostringlist'):
xml = '\r\n'.join(etree.tostringlist(root)) + '\r\n'
else:
xml = etree.tostring(root) + '\r\n'
return xml
示例8: _serialize_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def _serialize_xml(self, root):
"""Serialize XML data into string
It serializes the dynamic xml created and converts
it to a string. This is done before sending the
xml to the ILO.
:param root: root of the dynamic xml.
"""
if hasattr(etree, 'tostringlist'):
if six.PY3:
xml_content_list = [
x.decode("utf-8") for x in etree.tostringlist(root)]
else:
xml_content_list = etree.tostringlist(root)
xml = '\r\n'.join(xml_content_list) + '\r\n'
else:
if six.PY3:
xml_content = etree.tostring(root).decode("utf-8")
else:
xml_content = etree.tostring(root)
xml = xml_content + '\r\n'
return xml
示例9: process
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def process(path, style):
xml = ET.parse(path)
e = xml.getroot().find("n:head/n:style[@type='text/css']", NS)
if e is not None:
e.text="$$STYLE$$"
else:
print(f'WARNING: {path} has no style element')
for e in xml.getroot().findall(".//n:img", NS):
with open(path.parent / e.get('src'), 'rb') as f:
img = base64.b64encode(f.read()).decode()
e.set('src', 'data:image/png;base64,' + img)
xml_str = ET.tostringlist(xml.getroot(), encoding='unicode')
with open(path.with_suffix('.html'), 'w', encoding='utf-8') as f:
f.write(''.join(style if p == '$$STYLE$$' else p for p in xml_str))
示例10: createLog
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def createLog(lines):
root = xml.Element('django-objects', attrib={'version' : '1.0'})
for l in lines:
child_line = xml.SubElement(root, 'object', attrib={'pk' : str(l.id), 'model': "log.line"})
line_message = xml.SubElement(child_line, 'field', attrib={'type' : "TextField", 'name' : "message"})
line_message.text = formatMsg(l.message)
line_nick = xml.SubElement(child_line, 'field', attrib={'type' : "CharField", 'name' : "nick"})
line_nick.text = formatMsg(l.nick)
line_hostname = xml.SubElement(child_line, 'field', attrib={'type' : "CharField", 'name' : "hostname"})
line_hostname.text = formatMsg(l.hostname)
line_channel = xml.SubElement(child_line, 'field', attrib={'type' : "CharField", 'name' : "channel"})
line_channel.text = formatMsg(l.channel)
line_timestamp = xml.SubElement(child_line, 'field', attrib={'type' : "DateTimeField", 'name' : "timestamp"})
line_timestamp.text = str(l.timestamp)
line_msgType = xml.SubElement(child_line, 'field', attrib={'type' : "CharField", 'name' : "msgType"})
line_msgType.text = formatMsg(l.msgType)
return xml.tostringlist(root, encoding="utf8", method='xml')
示例11: write_adaptor_declaration
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def write_adaptor_declaration(self, interface_el, notifications, request_responses, out):
global prefix_class_item
def glue_strings(strings):
ret = list()
curstr = ""
for str in strings:
curstr = curstr + str
if str[-1] == ">":
ret.append(curstr)
curstr = ""
return ret
ifacename = interface_el.get("name")
out.write("class " + ifacename + "Adaptor : public QDBusAbstractAdaptor {\n")
out.write(" Q_OBJECT\n")
out.write(' Q_CLASSINFO("D-Bus Interface", "' + self.interface_path + "." + ifacename + '")\n')
out.write(' Q_CLASSINFO("D-Bus Introspection",\n')
introspection_el = self.create_introspection_iface_el(interface_el, "hmi")
introspection = glue_strings(ElementTree.tostringlist(introspection_el))
for str in introspection:
str = str.replace('"', '\\"')
out.write('"' + str + '"' + "\n")
out.write(" )\n")
out.write(" public:\n")
out.write(" explicit " + ifacename + "Adaptor(QObject *parent = 0);\n")
out.write(" void SetApi(Q%sItem*);\n" % prefix_class_item)
out.write(" DBusController *dbusController;\n")
out.write(" public slots:\n")
for (request, response) in request_responses:
signature = self.make_method_signature(request, response, ifacename, False)
out.write(" " + signature + ";\n")
out.write(" signals:\n")
for n in notifications:
signature = self.make_signal_signature(n, ifacename, True)
out.write(" " + signature + ";\n")
out.write(" private slots:\n")
for n in notifications:
signature = self.make_qml_signal_signature(n, ifacename, n.get("name") + "_qml", False)
out.write(" " + signature + ";\n")
out.write(" private:\n")
out.write(" Q%sItem* api_;\n" % prefix_class_item)
out.write("};\n\n")
示例12: cancel_tasks
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def cancel_tasks(self, gateway, task_uris=None):
'''Cancel queued tasks
'''
if not hasattr(gateway, 'tasks'):
return []
if task_uris is None:
task_uris = [task.href for task in gateway.tasks.task]
try:
for task_uri in task_uris:
self.driver.connection.request(task_uri + '/action/cancel',
method='POST')
except Exception as e:
log.error('Error cancelling task %r:', task_uri)
for line in ET.tostringlist(e.args[0]):
log.error(line)
raise
return task_uris
示例13: dumps
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def dumps(self):
''' Dump contents as a string in X3D format '''
xml = []
# Header
xml += ['<?xml version="1.0" encoding="UTF-8"?>\n']
xml += ['<!DOCTYPE %s>\n\n' % X3D_DOCTYPE]
# X3D body
xml += ET.tostringlist(self._root)
# reformat for multi-line printing
tag = None
lined = []
for chunk in xml:
lined.append(chunk)
if chunk.startswith('</'):
tag = 'close'
elif chunk.startswith('<'):
tag = 'open'
elif chunk.endswith('>'):
lined.append('\n')
tag = None
return ''.join(lined)
示例14: save_xml_result
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def save_xml_result(self):
if not self.ns.xmlpath and not self.testsuite_xml:
return
import xml.etree.ElementTree as ET
root = ET.Element("testsuites")
# Manually count the totals for the overall summary
totals = {'tests': 0, 'errors': 0, 'failures': 0}
for suite in self.testsuite_xml:
root.append(suite)
for k in totals:
try:
totals[k] += int(suite.get(k, 0))
except ValueError:
pass
for k, v in totals.items():
root.set(k, str(v))
xmlpath = os.path.join(support.SAVEDCWD, self.ns.xmlpath)
with open(xmlpath, 'wb') as f:
for s in ET.tostringlist(root):
f.write(s)
示例15: toSvg
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostringlist [as 别名]
def toSvg(self, onlySelected=False):
'Return selected or all items in the scene as an SVG document string'
if onlySelected:
import q2str
self._log.trace('selectionGroup: pos={}, transform={}'
, self.scene.selectionGroup.pos()
, q2str.FormatQTransform(self.scene.selectionGroup.transform()) )
svg_attribs = \
{ 'xmlns' : SVG_ns
, 'xmlns:tiles' : TILES_ns
, 'version' : '1.1'
, 'width' : str(self.scene.sceneRect().width())
, 'height' : str(self.scene.sceneRect().height())
}
doc = ET.Element('svg', attrib=svg_attribs)
scene_g = ET.SubElement(doc, 'g', transform='rotate({})'.format(self.graphicsView.GetRoll()))
for it in self.scene.items(order=QtCore.Qt.AscendingOrder):
if it.isSelected() or not onlySelected:
if hasattr(it, 'toSvg'):
e = it.toSvg(scene_g)
scene_g.append(e)
contents = '\n'.join([XML_decl] + ET.tostringlist(doc, encoding='unicode'))
self._log.trace('{}', contents)
return contents