本文整理汇总了Python中xml.etree.ElementTree.tostring方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.tostring方法的具体用法?Python ElementTree.tostring怎么用?Python ElementTree.tostring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.tostring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_model
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def get_model(self, mode="mujoco_py"):
"""
Returns a MjModel instance from the current xml tree.
"""
available_modes = ["mujoco_py"]
with io.StringIO() as string:
string.write(ET.tostring(self.root, encoding="unicode"))
if mode == "mujoco_py":
from mujoco_py import load_model_from_xml
model = load_model_from_xml(string.getvalue())
return model
raise ValueError(
"Unkown model mode: {}. Available options are: {}".format(
mode, ",".join(available_modes)
)
)
示例2: _do_scheme
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree 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: tvtunes_nfo
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def tvtunes_nfo(path, urls):
''' Create tvtunes.nfo
'''
try:
xml = etree.parse(path).getroot()
except Exception:
xml = etree.Element('tvtunes')
for elem in xml.getiterator('tvtunes'):
for file in list(elem):
elem.remove(file)
for url in urls:
etree.SubElement(xml, 'file').text = url
indent(xml)
write_xml(etree.tostring(xml, 'UTF-8'), path)
示例4: node_index
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def node_index(self, folder, view, mixed=False):
file = os.path.join(folder, "index.xml")
index = self.sync['SortedViews'].index(view['Id'])
try:
xml = etree.parse(file).getroot()
xml.set('order', str(index))
except Exception:
xml = self.node_root('main', index)
etree.SubElement(xml, 'label')
label = xml.find('label')
label.text = view['Name'] if not mixed else "%s (%s)" % (view['Name'], _(view['Media']))
indent(xml)
write_xml(etree.tostring(xml, 'UTF-8'), file)
示例5: applyall
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def applyall(cls, parent):
device = parent.nearest_pandevice()
logger.debug(device.id + ": applyall called on %s type" % cls)
objects = parent.findall(cls)
if not objects:
return
# Create the xpath
xpath = objects[0].xpath_nosuffix()
# Create the root element
lasttag = cls.XPATH.rsplit("/", 1)[-1]
element = ET.Element(lasttag)
# Build the full element from the objects
for obj in objects:
device.xml_combine(element, [obj.element(), ])
# Apply the element to the xpath
device.set_config_changed()
device.xapi.edit(xpath, ET.tostring(element, encoding='utf-8'), retry_on_peer=cls.HA_SYNC)
for obj in objects:
obj._check_child_methods("apply")
示例6: op
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def op(self, cmd=None, vsys=None, xml=False, cmd_xml=True, extra_qs=None, retry_on_peer=False):
"""Perform operational command on this device
Args:
cmd (str): The operational command to execute
vsys (str): Vsys id.
xml (bool): Return value should be a string (Default: False)
cmd_xml (bool): True: cmd is not XML, False: cmd is XML (Default: True)
extra_qs: Extra parameters for API call
retry_on_peer (bool): Try on active Firewall first, then try on passive Firewall
Returns:
xml.etree.ElementTree: The result of the operational command. May also return a string of XML if xml=True
"""
element = self.xapi.op(cmd, vsys, cmd_xml, extra_qs, retry_on_peer=retry_on_peer)
if xml:
return ET.tostring(element, encoding='utf-8')
else:
return element
示例7: add_commit_lock
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def add_commit_lock(self, comment=None, scope="shared", exceptions=True, retry_on_peer=True):
self._logger.debug("%s: Add commit lock requested for scope %s" % (self.id, scope))
cmd = ET.Element("request")
subel = ET.SubElement(cmd, "commit-lock")
subel = ET.SubElement(subel, "add")
if comment is not None:
subel = ET.SubElement(subel, "comment")
subel.text = comment
try:
self.xapi.op(ET.tostring(cmd, encoding='utf-8'), vsys=scope, retry_on_peer=retry_on_peer)
except (pan.xapi.PanXapiError, err.PanDeviceXapiError) as e:
if not re.match(r"Commit lock is already held", str(e)):
raise
else:
if exceptions:
raise err.PanLockError(str(e), pan_device=self)
else:
self._logger.debug(str(e))
return False
self.commit_locked = True
return True
示例8: remove_commit_lock
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def remove_commit_lock(self, admin=None, scope="shared", exceptions=True, retry_on_peer=True):
self._logger.debug("%s: Remove commit lock requested for scope %s" % (self.id, scope))
cmd = ET.Element("request")
subel = ET.SubElement(cmd, "commit-lock")
subel = ET.SubElement(subel, "remove")
if admin is not None:
subel = ET.SubElement(subel, "admin")
subel.text = admin
try:
self.xapi.op(ET.tostring(cmd, encoding='utf-8'), vsys=scope, retry_on_peer=retry_on_peer)
except (pan.xapi.PanXapiError, err.PanDeviceXapiError) as e:
if not re.match(r"Commit lock is not currently held", str(e)):
raise
else:
if exceptions:
raise err.PanLockError(str(e), pan_device=self)
else:
self._logger.debug(str(e))
return False
self.commit_locked = False
return True
示例9: remove_config_lock
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def remove_config_lock(self, scope="shared", exceptions=True, retry_on_peer=True):
self._logger.debug("%s: Remove config lock requested for scope %s" % (self.id, scope))
cmd = ET.Element("request")
subel = ET.SubElement(cmd, "config-lock")
subel = ET.SubElement(subel, "remove")
try:
self.xapi.op(ET.tostring(cmd, encoding='utf-8'), vsys=scope, retry_on_peer=retry_on_peer)
except (pan.xapi.PanXapiError, err.PanDeviceXapiError) as e:
if not re.match(r"Config is not currently locked for scope (shared|vsys\d)", str(e)):
raise
else:
if exceptions:
raise err.PanLockError(str(e), pan_device=self)
else:
self._logger.debug(str(e))
return False
self.config_locked = False
return True
示例10: send
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def send(self, uidmessage):
"""Send a uidmessage to the User-ID API of a firewall
Used for adhoc User-ID API calls that are not supported by other
methods in this class. This method cannot be batched.
Args:
uidmessage (str): The UID Message in XML to send to the firewall
"""
if self._batch:
return
else:
cmd = ET.tostring(uidmessage)
try:
self.device.xapi.user_id(cmd=cmd, vsys=self.device.vsys)
except (err.PanDeviceXapiError, PanXapiError) as e:
# Check if this is just an error about duplicates or nonexistant tags
# If so, ignore the error. Most operations don't care about this.
message = str(e)
if self.ignore_dup_errors and (message.endswith("already exists, ignore") or message.endswith("does not exist, ignore unreg")):
return
else:
raise e
示例11: xml_root
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def xml_root(self):
if self.xml_element_root is None:
return None
s = etree.tostring(self.xml_element_root, encoding=_encoding)
if not s:
return None
self._log(DEBUG3, 'xml_root: %s', type(s))
self._log(DEBUG3, 'xml_root.decode(): %s', type(s.decode(_encoding)))
return s.decode(_encoding)
# XXX Unicode notes
# 2.7
# decode() str (bytes) -> unicode
# encode() unicode -> str (bytes)
# encode() of str will call decode()
# 3.x
# decode() bytes -> str (unicode)
# encode() str (unicode) -> bytes
# cannot encode() bytes
# cannot decode() str
示例12: xml_result
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def xml_result(self):
if self.element_result is None:
return None
s = ''.encode()
if self.element_result.text:
s += self.element_result.text.encode(_encoding)
for elem in self.element_result:
s += etree.tostring(elem, encoding=_encoding)
if not s:
return None
self._log(DEBUG3, 'xml_result: %s', type(s))
self._log(DEBUG3, 'xml_result.decode(): %s', type(s.decode(_encoding)))
return s.decode(_encoding)
示例13: _generate_chat
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def _generate_chat(self, to, from_, body):
data = _FormData()
data.add_text('from', from_, 'plain')
data.add_text('to', to, 'plain')
data.add_text('body', body, 'plain')
message_element = ElementTree.Element(
ElementTree.QName('jabber:client', 'message'),
{'from': from_, 'to': to, 'type': 'chat'})
body_element = ElementTree.SubElement(
message_element,
ElementTree.QName('jabber:client', 'body'))
body_element.text = body
data.add_text('stanza',
ElementTree.tostring(message_element, encoding='utf-8'),
'xml')
return data
示例14: _generate_presence_available
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
def _generate_presence_available(self, to, from_, show=None):
data = _FormData()
data.add_text('from', from_, 'plain')
data.add_text('to', to, 'plain')
# If the "presence" attribute is absent, "available" is assumed and it is
# not sent by Google Talk.
presence_element = ElementTree.Element(
ElementTree.QName('jabber:client', 'presence'),
{'from': from_, 'to': to})
if show: # This is currently a dead code path.
# The show element is optional according to RFC 3921, 2.2.2.1.
data.add_text('show', show, 'plain')
show_element = ElementTree.SubElement(
presence_element,
ElementTree.QName('jabber:client', 'show'))
show_element.text = show
data.add_text('stanza',
ElementTree.tostring(presence_element, 'utf-8'),
'xml')
return data
示例15: checkCobertura
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import tostring [as 别名]
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