本文整理汇总了Python中xml.etree.cElementTree.Element.text方法的典型用法代码示例。如果您正苦于以下问题:Python Element.text方法的具体用法?Python Element.text怎么用?Python Element.text使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.cElementTree.Element
的用法示例。
在下文中一共展示了Element.text方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_metadata_slice_node
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def build_metadata_slice_node(self, data_slice):
#Building metadata
metadata_node = Element(self.SLICE_METADATA)
#Adding info
#indicator-ref
indicator_ref_node = Element(self.INDICATOR_REF)
indicator_ref_node.attrib[self.INDICATOR_ATT_ID] = data_slice.indicator.indicator_id
metadata_node.append(indicator_ref_node)
#time/region
if isinstance(data_slice.dimension, Time):
metadata_node.append(self.build_time_node(data_slice.dimension))
elif isinstance(data_slice.dimension, Region):
if type(data_slice.dimension) == Region:
region_node = Element(self.OBSERVATION_REGION)
region_node.text = self.OBSERVATION_ATT_COUNTRY_PREFIX \
+ data_slice.dimension.un_code
metadata_node.append(region_node)
elif type(data_slice.dimension) == Country:
country_node = Element(self.OBSERVATION_COUNTRY)
country_node.text = str(data_slice.dimension.iso3) # It will have it
metadata_node.append(country_node)
else:
raise RuntimeError("Unrecognized area type {0} while building slice. Impossible to generate xml".
format(type(data_slice.dimension)))
else:
raise RuntimeError("Unknown dimension while building slice.")
#Returnin node
return metadata_node
示例2: build_time_node
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def build_time_node(self, ref_time):
#Building top node
time_node = Element(self.TIME)
#Managging different time instances
if type(ref_time) is Instant:
time_node.attrib[self.TIME_ATT_UNIT] = "instant"
time_node.text = ref_time.get_time_string()
elif type(ref_time) is YearInterval:
time_node.attrib[self.TIME_ATT_UNIT] = "years"
time_node.text = ref_time.get_time_string()
elif type(ref_time) is MonthInterval:
time_node.attrib[self.TIME_ATT_UNIT] = "months"
time_node.text = ref_time.get_time_string()
elif type(ref_time) is Interval:
if ref_time.frequency == Interval.YEARLY:
time_node.attrib[self.TIME_ATT_UNIT] = "years"
else:
time_node.attrib[self.TIME_ATT_UNIT] = "months"
interval_node = Element(self.TIME_INTERVAL)
beg_node = Element(self.TIME_INTERVAL_BEG)
beg_node.text = str(ref_time.start_time)
end_node = Element(self.TIME_INTERVAL_END)
end_node.text = str(ref_time.end_time)
interval_node.append(beg_node)
interval_node.append(end_node)
time_node.append(interval_node)
else:
raise RuntimeError("Unrecognized time type. Impossible to build node")
#Returning final node
return time_node
示例3: create_xml
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def create_xml(self, filename):
root = Element("players")
tree = ElementTree(root)
for record in self:
player = Element('player')
first_name = Element('first_name')
last_name = Element('last_name')
salary = Element('salary')
player.set('year', str(record.year_played))
first_name.text = record.first_name
last_name.text = record.last_name
salary.text = '${sal:,.2f}'.format(sal=record.salary)
player.append(first_name)
player.append(last_name)
player.append(salary)
root.append(player)
from xml.dom import minidom
xml_str = etree.tostring(root)
pretty_xml = minidom.parseString(xml_str).toprettyxml(indent=' ', encoding='utf8')
xml_results = pretty_xml.decode()
try:
with open(filename, 'w', encoding='utf8') as f_out:
f_out.write(xml_results)
except IOError as e:
print(e)
示例4: write_everything_from_google_to_xml
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def write_everything_from_google_to_xml(country, outfile='weather.xml', hl=''):
""" Write all the results from google to an xml file """
weather_reports = pywapi.get_everything_from_google(country, hl)
xml_output = Element('Weather')
for city in weather_reports:
try:
xml_city = Element('town')
xml_name = Element('name')
xml_name.text = city
xml_city.append(xml_name)
xml_temperature = Element('temperature')
xml_temperature.text = weather_reports[city]['current_conditions']['temp_c']
xml_city.append(xml_temperature)
xml_humidity = Element('humidity')
xml_humidity.text = weather_reports[city]['current_conditions']['humidity']
xml_city.append(xml_humidity)
xml_condition = Element('condition')
xml_condition.text = weather_reports[city]['current_conditions']['condition']
xml_city.append(xml_condition)
xml_wind = Element('wind')
xml_wind.text = weather_reports[city]['current_conditions']['wind_condition']
xml_city.append(xml_wind)
xml_output.append(xml_city)
except KeyError:
pass
ElementTree(xml_output).write(outfile, 'UTF-8')
示例5: _fill_in_location_element
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def _fill_in_location_element(xml_root, location, data_fields):
fixture_fields = [
'name',
'site_code',
'external_id',
'latitude',
'longitude',
'location_type',
'supply_point_id',
]
for field in fixture_fields:
field_node = Element(field)
val = getattr(location, field)
field_node.text = six.text_type(val if val is not None else '')
xml_root.append(field_node)
# in order to be indexed, custom data fields need to be top-level
# so we stick them in there with the prefix data_
for field in data_fields:
if field.index_in_fixture:
field_node = Element(_get_indexed_field_name(field.slug))
val = location.metadata.get(field.slug)
field_node.text = six.text_type(val if val is not None else '')
xml_root.append(field_node)
xml_root.append(_get_metadata_node(location, data_fields))
示例6: build_license_node
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def build_license_node(self):
#Building node
license_node = Element(self.LICENSE)
#Attaching info
#name
name_node = Element(self.LICENSE_NAME)
name_node.text = self._dataset.license_type.name
license_node.append(name_node)
#description
desc_node = Element(self.LICENSE_DESCRIPTION)
desc_node.text = self._dataset.license_type.description
license_node.append(desc_node)
#republish
republish_node = Element(self.LICENSE_REPUBLISH)
republish_node.text = str(self._dataset.license_type.republish)
license_node.append(republish_node)
#url
url_node = Element(self.LICENSE_URL)
url_node.text = self._dataset.license_type.url
license_node.append(url_node)
#Attaching node to root
self._root.append(license_node)
示例7: create_IATI_xml
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def create_IATI_xml(iatidata, dir, o):
#iatidata contains the activities
#o contains the organisation data
output = ''
node = Element('iati-activities')
node.set("version", "1.03")
current_datetime = datetime.now().replace(microsecond=0).isoformat()
node.set("generated-datetime",current_datetime)
node.append(Comment('generated by CSV2IATI 2.3'))
character_encoding = o.get("data-encoding-override") or o["data-encoding"]
for activity in iatidata:
#for each activity, create one <iati-activity>
a = Element("iati-activity")
a.set("xml:lang", o["lang"])
a.set("default-currency", o["default-currency"])
a.set("last-updated-datetime", current_datetime)
node.append(a)
ro = Element("reporting-org")
ro.set("ref", o["reporting-org"]["ref"])
ro.set("type", o["reporting-org"]["type"])
ro.text = o["reporting-org"]["text"]
a.append(ro)
if "add-to-activities" in o["contact-info"]:
contact_info = Element("contact-info")
person_name = Element("person-name")
person_name.text = o["contact-info"]["person-name"]
telephone = Element("telephone")
telephone.text = o["contact-info"]["telephone"]
email = Element("email")
email.text = o["contact-info"]["email"]
address = Element("mailing-address")
address.text = o["contact-info"]["address"]
contact_info.append(person_name)
contact_info.append(telephone)
contact_info.append(email)
contact_info.append(address)
a.append(contact_info)
for field in activity:
#e.g. activity['activity-date']
for key, val in field.items():
#e.g. activity['activity-date']['fields']
if type(val) == dict:
append_recursive(key,val,a)
else:
if val != '':
a.set(key, val)
doc = ElementTree(node)
XMLfile = str(time.time()) + '.xml'
XMLfilename = dir + '/' + XMLfile
XMLabsfilename = UPLOAD_FILES_BASE + dir + '/' + XMLfile
indent(node)
doc.write(XMLabsfilename, encoding="utf-8", xml_declaration=True)
XMLfilename_html = request.url_root + XMLfilename
return XMLfilename_html
示例8: attach_value_to_observation
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def attach_value_to_observation(self, obs_node, data_obs):
#Adding obligatory node obs-status
status_node = Element(self.OBSERVATION_OBS_STATUS)
status = data_obs.value.obs_status
status_node.text = status
obs_node.append(status_node)
#Adding value if needed
if not status == data_obs.value.MISSING:
value_node = Element(self.OBSERVATION_VALUE)
value_node.text = str(data_obs.value.value)
obs_node.append(value_node)
示例9: build_observation_node
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def build_observation_node(self, data_obs):
#Building node
observation_node = Element(self.OBSERVATION)
#Attaching info
#id (attrib.)
observation_node.attrib[self.OBSERVATION_ATT_ID] = \
str(data_obs.observation_id)
#issued
issued_node = Element(self.OBSERVATION_ISSUED)
issued_node.text = data_obs.issued.get_time_string()
observation_node.append(issued_node)
#obs-staus, value
self.attach_value_to_observation(observation_node, data_obs)
#computation
computation_node = Element(self.OBSERVATION_COMPUTATION)
computation_node.attrib[self.OBSERVATION_COMPUTATION_TYPE_ATT] = data_obs.computation.uri
computation_node.text = Computation.get_desc_of_uri(data_obs.computation.uri)
observation_node.append(computation_node)
if type(data_obs.region) == Region:
region_node = Element(self.OBSERVATION_REGION)
region_node.text = self.OBSERVATION_ATT_COUNTRY_PREFIX + str(data_obs.region.un_code)
observation_node.append(region_node)
elif type(data_obs.region) == Country:
country_node = Element(self.OBSERVATION_COUNTRY)
country_node.text = str(data_obs.region.iso3) # It will have it, do not worry.
observation_node.append(country_node)
else:
raise RuntimeError("Unrecognized area type {0} while building observation. Unable to build xml".
format(type(data_obs.region)))
#time
observation_node.append(self.build_time_node(data_obs.ref_time))
#indicator
indicator_ref_node = Element(self.INDICATOR_REF)
indicator_ref_node.attrib[self.OBSERVATION_INDICATOR] = \
self.OBSERVATION_ATT_INDICATOR_PREFIX \
+ str(data_obs.indicator.indicator_id)
self.include_indicator_if_needed(data_obs.indicator) # Managing ind. info
observation_node.append(indicator_ref_node)
#Attaching optional group info
self.attach_groups_info_if_needed(observation_node, data_obs)
return observation_node
示例10: _extract_indicator_name_nodes
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def _extract_indicator_name_nodes(self, data_indicator):
result = []
#EN
node_name_en = Element(self.INDICATOR_NAME_EN)
node_name_en.text = data_indicator.name_en
result.append(node_name_en)
#ES
node_name_es = Element(self.INDICATOR_NAME_ES)
node_name_es.text = data_indicator.name_es
result.append(node_name_es)
#FR
node_name_fr = Element(self.INDICATOR_NAME_FR)
node_name_fr.text = data_indicator.name_fr
result.append(node_name_fr)
return result
示例11: _set_text
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def _set_text(self, tag, text):
elem = self._xmlnode.find(tag)
if text != None:
if elem == None:
elem = Element(tag)
self._xmlnode.append(elem)
elem.text = text
示例12: get_attr_id
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def get_attr_id(self, title, attr_type, edge_or_node, default, mode):
# find the id of the attribute or generate a new id
try:
return self.attr[edge_or_node][mode][title]
except KeyError:
# generate new id
new_id = str(next(self.attr_id))
self.attr[edge_or_node][mode][title] = new_id
attr_kwargs = {'id': new_id, 'title': title, 'type': attr_type}
attribute = Element('attribute', **attr_kwargs)
# add subelement for data default value if present
default_title = default.get(title)
if default_title is not None:
default_element = Element('default')
default_element.text = make_str(default_title)
attribute.append(default_element)
# new insert it into the XML
attributes_element = None
for a in self.graph_element.findall('attributes'):
# find existing attributes element by class and mode
a_class = a.get('class')
a_mode = a.get('mode', 'static') # default mode is static
if a_class == edge_or_node and a_mode == mode:
attributes_element = a
if attributes_element is None:
# create new attributes element
attr_kwargs = {'mode': mode, 'class': edge_or_node}
attributes_element = Element('attributes', **attr_kwargs)
self.graph_element.insert(0, attributes_element)
attributes_element.append(attribute)
return new_id
示例13: list_to_xml
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def list_to_xml(l, item):
el = Element("data")
for val in l:
child = Element(item)
child.text = str(val)
el.append(child)
print(tostring(el))
示例14: iq_handler
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def iq_handler(self, xml):
iq = CloudDotIQ(xml)
print "Got IQ", type(iq), iq
data = iq.data
print "Data:", repr(data)
numBytes = iq.numReturnBytes
# Set the DM's flag that we're using the device.
# This is definitely incorrect, but it may be good enough.
self.dm.scanEvent.wait()
try:
self.dm.scanEvent.clear()
self.device.write(data, modbus=True, checksum=False)
result = self.device.read(numBytes, modbus=True)
result = struct.pack("B" * len(result), *result)
finally:
self.dm.scanEvent.set()
# We have the result, send it back in the response.
etIq = self.Iq(xml=xml)
result = base64.b64encode(result)
reply = etIq.reply()
dataElem = Element("data")
dataElem.text = result
qt = Element("query", {"xmlns": "jabber:iq:clouddot"})
qt.append(dataElem)
print "qt", qt
reply.appendxml(qt)
print "etIq.reply() redux:", reply
reply.send(block=False)
示例15: rss2
# 需要导入模块: from xml.etree.cElementTree import Element [as 别名]
# 或者: from xml.etree.cElementTree.Element import text [as 别名]
def rss2(feed, pretty_print=True):
indent = '\n ' if pretty_print else ''
indent2 = '\n ' if pretty_print else ''
rss = Element('rss', version='2.0')
rss.text = '\n ' if pretty_print else ''
channel = SubElement(rss, 'channel')
channel.text = indent
channel.tail = '\n' if pretty_print else ''
set_rss2_text(SubElement(channel, 'title'), feed.title)
set_rss2_text(SubElement(channel, 'description'), feed.subtitle or '')
SubElement(channel, 'link').text = feed.link
SubElement(channel, 'lastBuildDate').text = rss2_date(feed.updated)
if feed.language: SubElement(channel, 'language').text = feed.language
if feed.rights: SubElement(channel, 'copyright').text = feed.rights
if feed.logo:
image = SubElement(channel, 'image')
image.text = indent2
SubElement(image, 'url').text = feed.logo
SubElement(image, 'title').text = ''
SubElement(image, 'link').text = feed.link
for child in image: child.tail = indent2
image[-1].tail = '\n ' if pretty_print else ''
for entry in feed.entries:
item = entry.rss2(pretty_print)
item[-1].tail = indent
channel.append(item)
for child in channel: child.tail = indent
channel[-1].tail = '\n ' if pretty_print else ''
return rss