本文整理汇总了Python中defusedxml.ElementTree.fromstring方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.fromstring方法的具体用法?Python ElementTree.fromstring怎么用?Python ElementTree.fromstring使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类defusedxml.ElementTree
的用法示例。
在下文中一共展示了ElementTree.fromstring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_node_pxe
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def set_node_pxe(self, node):
"""Set a node to PXE boot first."""
ses = self.init_session(node)
domain = ses.lookupByName(node.name)
domain_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_SECURE
| libvirt.VIR_DOMAIN_XML_INACTIVE)
xmltree = ET.fromstring(domain_xml)
# Delete all the current boot entries
os_tree = xmltree.find("./os")
boot_elements = os_tree.findall("./boot")
for e in boot_elements:
os_tree.remove(e)
# Now apply our boot order which is 'network' and then 'hd'
os_tree.append(ET.fromstring("<boot dev='network' />"))
os_tree.append(ET.fromstring("<boot dev='hd' />"))
# And now save the new XML def to the hypervisor
domain_xml = ET.tostring(xmltree, encoding="utf-8")
ses.defineXML(domain_xml.decode('utf-8'))
ses.close()
示例2: get_json_equivalent_from_xml_feed
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def get_json_equivalent_from_xml_feed(feed):
def internal_iter(tree, accum):
if tree is None:
return accum
if tree.getchildren():
accum[tree.tag] = {}
for each in tree.getchildren():
result = internal_iter(each, {})
if each.tag in accum[tree.tag]:
if not isinstance(accum[tree.tag][each.tag], list):
accum[tree.tag][each.tag] = [
accum[tree.tag][each.tag]
]
accum[tree.tag][each.tag].append(result[each.tag])
else:
accum[tree.tag].update(result)
else:
accum[tree.tag] = tree.text
return accum
return internal_iter(ElementTree.fromstring(feed), {})
示例3: _ParseRelationshipsXMLFile
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def _ParseRelationshipsXMLFile(self, xml_data):
"""Parses the relationships XML file (_rels/.rels).
Args:
xml_data (bytes): data of a _rels/.rels XML file.
Returns:
list[str]: property file paths. The path is relative to the root of
the ZIP file.
Raises:
zipfile.BadZipfile: if the relationship XML file cannot be read.
"""
xml_root = ElementTree.fromstring(xml_data)
property_files = []
for xml_element in xml_root.iter():
type_attribute = xml_element.get('Type')
if 'properties' in repr(type_attribute):
target_attribute = xml_element.get('Target')
property_files.append(target_attribute)
return property_files
示例4: list_level4_dataset_ids
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def list_level4_dataset_ids(self):
'''Convenience function which returns an up-to-date \
list of level4 dataset id's.
:returns: a comma-seperated list of level4 dataset id's
'''
podaac = p.Podaac()
data = podaac.dataset_search(process_level='4', items_per_page='400')
root = ET.fromstring(data.encode('utf-8'))
dataset_ids = []
for entry in root.findall('{http://www.w3.org/2005/Atom}entry'):
dataset_id = entry.find(
'{https://podaac.jpl.nasa.gov/opensearch/}datasetId').text
dataset_ids.append(dataset_id)
return dataset_ids
示例5: list_level4_dataset_short_names
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def list_level4_dataset_short_names(self):
'''Convenience function which returns an up-to-date \
list of level4 dataset short names.
:returns: a comma-seperated list of level4 dataset short names.
'''
podaac = p.Podaac()
data = podaac.dataset_search(process_level='4', items_per_page='400')
l4_dataset_short_names = []
root = ET.fromstring(data.encode('utf-8'))
for entry in root.findall('{http://www.w3.org/2005/Atom}entry'):
l4_dataset_short_name = entry.find(
'{https://podaac.jpl.nasa.gov/opensearch/}shortName').text
l4_dataset_short_names.append(l4_dataset_short_name)
return l4_dataset_short_names
示例6: test_dataset_metadata
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def test_dataset_metadata(self):
dataset_id = 'PODAAC-CCF35-01AD5'
dataset_short_name = 'CCMP_MEASURES_ATLAS_L4_OW_L3_5A_5DAY_WIND_VECTORS_FLK'
dataset_md = self.podaac.dataset_metadata(
dataset_id, dataset_short_name)
root = ET.fromstring(dataset_md.encode('utf-8'))
short_name = root[1][0].attrib
assert dataset_md is not None
assert str(short_name['id']) == dataset_short_name
assert_raises(requests.exceptions.HTTPError,
self.podaac.dataset_metadata,
'PODAAC-CCF35-01AD5',
'CCMP_MEASURES_ATLAS_L4_OW_L3_5A_5DAY_WIND_VECTORS_FLK',
'is')
assert_raises(Exception, self.podaac.dataset_metadata,
short_name='CCMP_MEASURES_ATLAS_L4_OW_L3_5A_5DAY_WIND_VECTORS_FLK')
# test case for the fucntion granule_metadata()
示例7: test_last24hours_datacasting_granule_md
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def test_last24hours_datacasting_granule_md(self):
dataset_id = 'PODAAC-ASOP2-25X01'
dataset_short_name = 'ASCATA-L2-25km'
_format = 'datacasting'
items_per_page = 10
granule_md = self.podaac.last24hours_datacasting_granule_md(
dataset_id, dataset_short_name, _format, items_per_page)
root = ET.fromstring(granule_md.encode('utf-8'))
dataset_id_ = root[0][3].text
assert granule_md is not None
assert dataset_id_ == dataset_id
assert_raises(requests.exceptions.HTTPError,
self.podaac.last24hours_datacasting_granule_md,
'PODAAC-ASOP2-25X01', 'ASCATA-L2-25km', _format='iso')
assert_raises(Exception, self.podaac.last24hours_datacasting_granule_md,
short_name='ASCATA-L2-25km', _format='iso')
# test case for the function dataset_variables
示例8: get_bugzilla_bug
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def get_bugzilla_bug(bugzilla_url, bug_id):
'''
Read bug XML, return all fields and values in a dictionary.
'''
bug_xml = _fetch_bug_content(bugzilla_url, bug_id)
tree = ElementTree.fromstring(bug_xml)
bug_fields = {
"long_desc": [],
"attachment": [],
"cc": [],
}
for bug in tree:
for field in bug:
if field.tag in ("long_desc", "attachment"):
new = {}
for data in field:
new[data.tag] = data.text
bug_fields[field.tag].append(new)
elif field.tag == "cc":
bug_fields[field.tag].append(field.text)
else:
bug_fields[field.tag] = field.text
return bug_fields
示例9: apply_logicalnames
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def apply_logicalnames(self, site_design, state_manager):
"""Gets the logicalnames for devices from lshw.
:param site_design: SiteDesign object.
:param state_manager: DrydockState object.
:return: Returns sets a dictionary of aliases that map to logicalnames in self.logicalnames.
"""
logicalnames = {}
results = state_manager.get_build_data(
node_name=self.get_name(), latest=True)
xml_data = None
for result in results:
if result.generator == "lshw":
xml_data = result.data_element
break
if xml_data:
xml_root = fromstring(xml_data)
try:
hardware_profile = site_design.get_hardware_profile(
self.hardware_profile)
for device in hardware_profile.devices:
logicalname = self._apply_logicalname(
xml_root, device.alias, device.bus_type,
device.address)
logicalnames[device.alias] = logicalname
except errors.DesignError:
self.logger.exception(
"Failed to load hardware profile while "
"resolving logical names for node %s", self.get_name())
raise
else:
self.logger.info(
"No Build Data found for node_name %s" % (self.get_name()))
self.logicalnames = logicalnames
示例10: backup_progress
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def backup_progress(self):
"""Return status of cloud backup as a dict.
Is there a way to get progress for Server version?
"""
epoch_time = int(time.time() * 1000)
if self.deploymentType == "Cloud":
url = (
self._options["server"] + "/rest/obm/1.0/getprogress?_=%i" % epoch_time
)
else:
logging.warning("This functionality is not available in Server version")
return None
r = self._session.get(url, headers=self._options["headers"])
# This is weird. I used to get xml, but now I'm getting json
try:
return json.loads(r.text)
except Exception:
import defusedxml.ElementTree as etree
progress = {}
try:
root = etree.fromstring(r.text)
except etree.ParseError as pe:
logging.warning(
"Unable to find backup info. You probably need to initiate a new backup. %s"
% pe
)
return None
for k in root.keys():
progress[k] = root.get(k)
return progress
示例11: _ParsePropertiesXMLFile
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def _ParsePropertiesXMLFile(self, xml_data):
"""Parses a properties XML file.
Args:
xml_data (bytes): data of a _rels/.rels XML file.
Returns:
dict[str, object]: properties.
Raises:
zipfile.BadZipfile: if the properties XML file cannot be read.
"""
xml_root = ElementTree.fromstring(xml_data)
properties = {}
for xml_element in xml_root.iter():
if not xml_element.text:
continue
# The property name is formatted as: {URL}name
# For example: {http://purl.org/dc/terms/}modified
_, _, name = xml_element.tag.partition('}')
# Do not including the 'lpstr' attribute because it is very verbose.
if name == 'lpstr':
continue
property_name = self._PROPERTY_NAMES.get(name, None)
if not property_name:
property_name = self._FormatPropertyName(name)
properties[property_name] = xml_element.text
return properties
示例12: _GetCreationTimeFromXMLString
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def _GetCreationTimeFromXMLString(
self, parser_mediator, record_index, xml_string):
"""Retrieves the creationg time from the XML string.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
record_index (int): event record index.
xml_string (str): event XML string.
Returns:
str: creation date and time formatted as ISO 8601 or None if not
available.
"""
xml_root = ElementTree.fromstring(xml_string)
system_xml_element = xml_root.find(
'{http://schemas.microsoft.com/win/2004/08/events/event}System')
if system_xml_element is None:
parser_mediator.ProduceExtractionWarning(
'missing System XML element in event record: {0:d}'.format(
record_index))
return None
time_created_xml_element = system_xml_element.find(
'{http://schemas.microsoft.com/win/2004/08/events/event}TimeCreated')
if time_created_xml_element is None:
parser_mediator.ProduceExtractionWarning(
'missing TimeCreated XML element in event record: {0:d}'.format(
record_index))
return None
return time_created_xml_element.get('SystemTime')
示例13: join_bigbluebutton
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def join_bigbluebutton(request: HttpRequest, meeting_id: str = REQ(validator=check_string),
password: str = REQ(validator=check_string),
checksum: str = REQ(validator=check_string)) -> HttpResponse:
if settings.BIG_BLUE_BUTTON_URL is None or settings.BIG_BLUE_BUTTON_SECRET is None:
return json_error(_("Big Blue Button is not configured."))
else:
response = requests.get(
add_query_to_redirect_url(settings.BIG_BLUE_BUTTON_URL + "api/create", urlencode({
"meetingID": meeting_id,
"moderatorPW": password,
"attendeePW": password + "a",
"checksum": checksum
})))
try:
response.raise_for_status()
except Exception:
return json_error(_("Error connecting to the Big Blue Button server."))
payload = ElementTree.fromstring(response.text)
if payload.find("messageKey").text == "checksumError":
return json_error(_("Error authenticating to the Big Blue Button server."))
if payload.find("returncode").text != "SUCCESS":
return json_error(_("Big Blue Button server returned an unexpected error."))
join_params = urlencode({ # type: ignore[type-var] # https://github.com/python/typeshed/issues/4234
"meetingID": meeting_id,
"password": password,
"fullName": request.user.full_name
}, quote_via=quote)
checksum = hashlib.sha1(("join" + join_params + settings.BIG_BLUE_BUTTON_SECRET).encode()).hexdigest()
redirect_url_base = add_query_to_redirect_url(settings.BIG_BLUE_BUTTON_URL + "api/join", join_params)
return redirect(add_query_arg_to_redirect_url(redirect_url_base, "checksum=" + checksum))
示例14: parse_content
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def parse_content(self, content):
"""
All child classes inherit this function to parse XML file automatically.
It will call the function :func:`parse_dom` by default to
parser all necessary data to :attr:`data` and the :attr:`xmlns` (the
default namespace) is ready for this function.
"""
self.dom = self.xmlns = None
self.data = {}
# ignore empty xml file
if len(content) > 3:
self.raw = '\n'.join(content)
self.dom = ET.fromstring(self.raw)
self.xmlns = self.dom.tag.strip("{").split("}")[0] if all(c in self.dom.tag for c in ["{", "}"]) else ""
self.data = self.parse_dom()
示例15: get_base
# 需要导入模块: from defusedxml import ElementTree [as 别名]
# 或者: from defusedxml.ElementTree import fromstring [as 别名]
def get_base(provider, **conn):
# Get the SAML Provider information
saml_provider = boto_get_saml_provider(provider['Arn'], **conn)
# Parse the SAML Metadata XML Document
root = ET.fromstring(saml_provider['SAMLMetadataDocument'])
saml_x509 = ''
company = ''
given_name = ''
email_address = ''
for parent in root.iter():
for child in parent:
if 'X509Certificate' in child.tag:
saml_x509 = child.text
if 'Company' in child.tag:
company = child.text
if 'GivenName' in child.tag:
given_name = child.text
if 'EmailAddress' in child.tag:
email_address = child.text
return {
'Name': root.attrib['entityID'],
'CreateDate': str(saml_provider['CreateDate']),
'ValidUntil': str(saml_provider['ValidUntil']),
'X509': saml_x509,
'Company': company,
'GivenName': given_name,
'Email': email_address
}