def to_xml(self):
"""Creates an ``ET.Element`` representing self, then returns it.
:returns root, an ``ET.Element`` representing this scheme.
"""
root = ET.Element("scheme")
ET.SubElement(root, "title").text = self.title
# add a description subelement if it's defined
if self.description is not None:
ET.SubElement(root, "description").text = self.description
# add all other subelements to this Scheme, represented by (tag, text)
subelements = [
("use_external_validation", self.use_external_validation),
("use_single_instance", self.use_single_instance),
("streaming_mode", self.streaming_mode)
]
for name, value in subelements:
ET.SubElement(root, name).text = str(value).lower()
endpoint = ET.SubElement(root, "endpoint")
args = ET.SubElement(endpoint, "args")
# add arguments as subelements to the <args> element
for arg in self.arguments:
arg.add_to_document(args)
return root
python类SubElement()的实例源码
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 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 __walk(self, node, parent):
name = self.__genName(node.tag)
tag = self.__getNamespace(node.tag)
if parent is None:
self.root = name
self.lines.append("%s = ET.Element(%s)" % (name, tag))
else:
self.lines.append("%s = ET.SubElement(%s, %s)" % (name, parent, tag))
# handles text
try:
t = node.text.strip()
if t == '': t = None
except:
t = None
if t is not None:
self.lines.append("%s.text = kwargs.get('', '%s') # PARAMETERIZE" % (name, t))
# handles attributes
for key,val in node.items():
key = self.__getNamespace(key)
self.lines.append("%s.set(%s, kwargs.get('', '%s')) # PARAMETERIZE" % (name, key, val))
for i in node.getchildren():
self.__walk(i, name)
def add_to_document(self, parent):
"""Adds an ``Argument`` object to this ElementTree document.
Adds an <arg> subelement to the parent element, typically <args>
and sets up its subelements with their respective text.
:param parent: An ``ET.Element`` to be the parent of a new <arg> subelement
:returns: An ``ET.Element`` object representing this argument.
"""
arg = ET.SubElement(parent, "arg")
arg.set("name", self.name)
if self.title is not None:
ET.SubElement(arg, "title").text = self.title
if self.description is not None:
ET.SubElement(arg, "description").text = self.description
if self.validation is not None:
ET.SubElement(arg, "validation").text = self.validation
# add all other subelements to this Argument, represented by (tag, text)
subelements = [
("data_type", self.data_type),
("required_on_edit", self.required_on_edit),
("required_on_create", self.required_on_create)
]
for name, value in subelements:
ET.SubElement(arg, name).text = str(value).lower()
return arg
def to_xml(self):
"""Creates an ``ET.Element`` representing self, then returns it.
:returns root, an ``ET.Element`` representing this scheme.
"""
root = ET.Element("scheme")
ET.SubElement(root, "title").text = self.title
# add a description subelement if it's defined
if self.description is not None:
ET.SubElement(root, "description").text = self.description
# add all other subelements to this Scheme, represented by (tag, text)
subelements = [
("use_external_validation", self.use_external_validation),
("use_single_instance", self.use_single_instance),
("streaming_mode", self.streaming_mode)
]
for name, value in subelements:
ET.SubElement(root, name).text = str(value).lower()
endpoint = ET.SubElement(root, "endpoint")
args = ET.SubElement(endpoint, "args")
# add arguments as subelements to the <args> element
for arg in self.arguments:
arg.add_to_document(args)
return root
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 _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 _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 export_orders(self):
for order in self.item_processor.yield_item(Order):
order_element = ET.SubElement(self.root, u'????????')
ET.SubElement(order_element, u'??').text = six.text_type(order.id)
ET.SubElement(order_element, u'?????').text = six.text_type(order.number)
ET.SubElement(order_element, u'????').text = six.text_type(order.date.strftime('%Y-%m-%d'))
ET.SubElement(order_element, u'?????').text = six.text_type(order.time.strftime('%H:%M:%S'))
ET.SubElement(order_element, u'???????????').text = six.text_type(order.operation)
ET.SubElement(order_element, u'????').text = six.text_type(order.role)
ET.SubElement(order_element, u'??????').text = six.text_type(order.currency_name)
ET.SubElement(order_element, u'????').text = six.text_type(order.currency_rate)
ET.SubElement(order_element, u'?????').text = six.text_type(order.sum)
ET.SubElement(order_element, u'???????????').text = six.text_type(order.comment)
clients_element = ET.SubElement(order_element, u'???????????')
client_element = ET.SubElement(clients_element, u'??????????')
ET.SubElement(client_element, u'??').text = six.text_type(order.client.id)
ET.SubElement(client_element, u'????????????').text = six.text_type(order.client.name)
ET.SubElement(client_element, u'????').text = six.text_type(order.client.role)
ET.SubElement(client_element, u'??????????????????').text = six.text_type(order.client.full_name)
ET.SubElement(client_element, u'???????').text = six.text_type(order.client.last_name)
ET.SubElement(client_element, u'???').text = six.text_type(order.client.first_name)
address_element = ET.SubElement(clients_element, u'????????????????')
ET.SubElement(clients_element, u'?????????????').text = six.text_type(order.client.address)
products_element = ET.SubElement(order_element, u'??????')
for order_item in order.items:
product_element = ET.SubElement(products_element, u'?????')
ET.SubElement(product_element, u'??').text = six.text_type(order_item.id)
ET.SubElement(product_element, u'????????????').text = six.text_type(order_item.name)
sku_element = ET.SubElement(product_element, u'?????????????? ')
sku_element.set(u'???', order_item.sku.id)
sku_element.set(u'??????????????????', order_item.sku.name_full)
sku_element.set(u'???????????????????????', order_item.sku.international_abbr)
sku_element.text = order_item.sku.name
ET.SubElement(product_element, u'?????????????').text = six.text_type(order_item.price)
ET.SubElement(product_element, u'??????????').text = six.text_type(order_item.quant)
ET.SubElement(product_element, u'?????').text = six.text_type(order_item.sum)
def backup_osm(self):
"""Writes OSM data as-is."""
osm = etree.Element('osm', version='0.6', generator=TITLE)
for osmel in self.osmdata.values():
el = osmel.to_xml()
if osmel.osm_type != 'node':
etree.SubElement(el, 'center', lat=str(osmel.lat), lon=str(osmel.lon))
osm.append(el)
return ("<?xml version='1.0' encoding='utf-8'?>\n" +
etree.tostring(osm, encoding='utf-8').decode('utf-8'))
def to_osc(self, josm=False):
"""Returns a string with osmChange or JOSM XML."""
osc = etree.Element('osm' if josm else 'osmChange', version='0.6', generator=TITLE)
if josm:
neg_id = -1
changeset = etree.SubElement(osc, 'changeset')
ch_tags = {
'source': self.source,
'created_by': TITLE,
'type': 'import'
}
for k, v in ch_tags.items():
etree.SubElement(changeset, 'tag', k=k, v=v)
for osmel in self.matched:
if osmel.action is not None:
el = osmel.to_xml()
if josm:
if osmel.action == 'create':
el.set('id', str(neg_id))
neg_id -= 1
else:
el.set('action', osmel.action)
osc.append(el)
else:
etree.SubElement(osc, osmel.action).append(el)
return ("<?xml version='1.0' encoding='utf-8'?>\n" +
etree.tostring(osc, encoding='utf-8').decode('utf-8'))
def saveTree(self,store):
"""
@description: save the treeview in the mama.xml file
@param: store
the listStore attach to the treeview
"""
# if there is still an entry in the model
config = expanduser('~') +'/.config/mama/mama.xml'
try:
if not os.path.exists(os.path.dirname(config)):
os.makedirs(os.path.dirname(config))
root = ET.Element("data")
if len(store) != 0:
for i in range(len(store)):
iter = store.get_iter(i)
if store[iter][0] != '' and store[iter][1] != '':
for s in store[iter][0].split('|'):
s = s.lower()
s = s.replace('*',' ')
Type = ET.SubElement(root, "entry")
Type.set("name",unicode(store[iter][2],"utf-8"))
Key = ET.SubElement(Type, "key")
Key.text = unicode(s,"utf-8")
Command = ET.SubElement(Type, "command")
Command.text = unicode(store[iter][1],"utf-8")
Linker = ET.SubElement(Type, "linker")
Spacebyplus = ET.SubElement(Type, "spacebyplus")
if store[iter][3] is not None or store[iter][4] is not None:
Linker.text = unicode(store[iter][3],"utf-8")
Spacebyplus.text = unicode(store[iter][4],"utf-8")
tree = ET.ElementTree(root).write(config,encoding="utf-8",xml_declaration=True)
except IOError:
print("Unable to write the file")
def saveTree(self, store):
"""
@description: save the treeview in the mama.xml file
@param: store
the listStore attach to the treeview
"""
# if there is still an entry in the model
config = expanduser('~') + '/.config/mama/mama.xml'
try:
if not os.path.exists(os.path.dirname(config)):
os.makedirs(os.path.dirname(config))
root = ET.Element("data")
if len(store) != 0:
for i in range(len(store)):
iter = store.get_iter(i)
if store[iter][0] != '' and store[iter][1] != '':
for s in store[iter][0].split('|'):
s = s.lower()
s = s.replace('*', ' ')
Type = ET.SubElement(root, "entry")
Type.set("name", unicode(store[iter][2], "utf-8"))
Key = ET.SubElement(Type, "key")
Key.text = unicode(s, "utf-8")
Command = ET.SubElement(Type, "command")
Command.text = unicode(store[iter][1], "utf-8")
Linker = ET.SubElement(Type, "linker")
Spacebyplus = ET.SubElement(Type, "spacebyplus")
if store[iter][3] is not None and store[iter][
4] is not None:
Linker.text = unicode(store[iter][3], "utf-8")
Spacebyplus.text = unicode(store[iter][4],
"utf-8")
tree = ET.ElementTree(root).write(config, encoding="utf-8",
xml_declaration=True)
except IOError:
print("Unable to write the file")
def saveTree(self, store):
"""
@description: save the treeview in the mama.xml file
@param: store
the listStore attach to the treeview
"""
# if there is still an entry in the model
config = expanduser('~') + '/.config/mama/mama.xml'
try:
if not os.path.exists(os.path.dirname(config)):
os.makedirs(os.path.dirname(config))
root = ET.Element("data")
if len(store) != 0:
for i in range(len(store)):
iter = store.get_iter(i)
if store[iter][0] != '' and store[iter][1] != '':
for s in store[iter][0].split('|'):
s = s.lower()
s = s.replace('*', ' ')
Type = ET.SubElement(root, "entry")
Type.set("name", unicode(store[iter][2], "utf-8"))
Key = ET.SubElement(Type, "key")
Key.text = unicode(s, "utf-8")
Command = ET.SubElement(Type, "command")
Command.text = unicode(store[iter][1], "utf-8")
Linker = ET.SubElement(Type, "linker")
Spacebyplus = ET.SubElement(Type, "spacebyplus")
if store[iter][3] is not None and store[iter][
4] is not None:
Linker.text = unicode(store[iter][3], "utf-8")
Spacebyplus.text = unicode(store[iter][4],
"utf-8")
ET.ElementTree(root).write(config, encoding="utf-8",
xml_declaration=True)
except IOError:
print("Unable to write the file")
def _generate_xml_common(self, parent):
"""
Generates the common XML elements of the XML element for this
:param xml.etree.ElementTree.Element parent: The parent XML element (i.e. the resource XML element).
"""
resource_name = SubElement(parent, 'ResourceName')
resource_name.text = self.name
# ----------------------------------------------------------------------------------------------------------------------
def generate_xml(self, parent):
"""
Generates the XML element for this resource.
:param xml.etree.ElementTree.Element parent: The parent XML element.
"""
resource = SubElement(parent, 'CountingResource')
self._generate_xml_common(resource)
amount = SubElement(resource, 'Amount')
amount.text = str(self.amount)
# ----------------------------------------------------------------------------------------------------------------------
def generate_xml(self, parent):
"""
Generates the XML element for this resource.
:param xml.etree.ElementTree.Element parent: The parent XML element.
"""
resource = SubElement(parent, 'ReadWriteLockResource')
self._generate_xml_common(resource)
# ----------------------------------------------------------------------------------------------------------------------