本文整理汇总了Python中xml.etree.cElementTree.ElementTree方法的典型用法代码示例。如果您正苦于以下问题:Python cElementTree.ElementTree方法的具体用法?Python cElementTree.ElementTree怎么用?Python cElementTree.ElementTree使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.cElementTree
的用法示例。
在下文中一共展示了cElementTree.ElementTree方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_xml
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def parse_xml(self, xml_file):
tree = ET.ElementTree(file=xml_file)
pwdFound = []
for elem in tree.iter():
values = {}
try:
if elem.attrib['name'].startswith('ftp') or elem.attrib['name'].startswith('ftps') or elem.attrib[
'name'].startswith('sftp') or elem.attrib['name'].startswith('http') or elem.attrib[
'name'].startswith('https'):
values['URL'] = elem.attrib['name']
encrypted_password = base64.b64decode(elem.attrib['value'])
password = win32crypt.CryptUnprotectData(encrypted_password, None, None, None, 0)[1]
values['Password'] = password
pwdFound.append(values)
except Exception, e:
pass
# print the results
示例2: update
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def update(self):
"""
根据最新数据获取更新ElementTree内容
"""
if self.natom != len(self.data):
raise UnmatchedDataShape(
'length of data is not equal to atom number.')
elif self.natom != len(self.tf):
raise UnmatchedDataShape(
'length of tf is not equal to atom number.')
elif self.natom != len(self.atom_names):
raise UnmatchedDataShape(
'length of atom names is not equal to atom number.')
# atoms info
self.update_atoms()
# space group
self.update_bases()
# Thermodynamic info.
self.update_name()
return
示例3: update_name
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def update_name(self):
"""
更新ElementTree中能量,力,作业路径等信息。
"""
value = ""
for key, attr in zip(['E', 'F', 'M'], ["energy", "force", "magnetism"]):
data = getattr(self, attr, 0.0)
value += "{}:{} ".format(key, data)
value = value.strip()
# Get current path.
path = getcwd()
value = "{} {}:{}".format(value, "P", path)
for elem in self.tree.iter("SymmetrySystem"):
elem.set("Name", value)
break
示例4: generate_settings_file
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def generate_settings_file(target_path):
source_path = xbmc.translatePath(
os.path.join(ADDON.getAddonInfo('path'), 'resources', 'settings.xml'))
root_target = ceT.Element("settings")
tree_source = eT.parse(source_path)
root_source = tree_source.getroot()
for item in root_source.findall('category'):
for setting in item.findall('setting'):
if 'id' in setting.attrib:
value = ''
if 'default' in setting.attrib:
value = setting.attrib['default']
ceT.SubElement(root_target, 'setting', id=setting.attrib['id'], value=value)
tree_target = ceT.ElementTree(root_target)
f = open(target_path, 'w')
tree_target.write(f)
f.close()
示例5: from_xml
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def from_xml(cls, xml, chunks_to_load=None, load_subtypes=True, type_separator=u"."):
if sem.misc.is_string(xml):
data = ET.parse(xml)
elif isinstance(xml, ET.ElementTree):
data = xml
elif isinstance(xml, type(ET.Element("a"))): # did not ind a better way to do this
data = xml
else:
raise TypeError("Invalid type for loading XML-SEM document: {0}".format(type(xml)))
root = data.getroot()
if root.tag != "sem":
raise ValueError("Not sem xml file type: '{0}'".format(root.tag))
doc_list = []
for document in list(root):
doc_list.append(Document.from_xml(document))
return SEMCorpus(doc_list)
示例6: newXMLPASCALfile
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def newXMLPASCALfile(imageheight, imagewidth, path, basename):
# print(filename)
annotation = ET.Element("annotation", verified="yes")
ET.SubElement(annotation, "folder").text = "images"
ET.SubElement(annotation, "filename").text = basename
ET.SubElement(annotation, "path").text = path
source = ET.SubElement(annotation, "source")
ET.SubElement(source, "database").text = "test"
size = ET.SubElement(annotation, "size")
ET.SubElement(size, "width").text = str(imagewidth)
ET.SubElement(size, "height").text = str(imageheight)
ET.SubElement(size, "depth").text = "3"
ET.SubElement(annotation, "segmented").text = "0"
tree = ET.ElementTree(annotation)
# tree.write("filename.xml")
return tree
示例7: saveMean
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def saveMean(fname, data):
root = et.Element('opencv_storage')
et.SubElement(root, 'Channel').text = '3'
et.SubElement(root, 'Row').text = str(imgSize)
et.SubElement(root, 'Col').text = str(imgSize)
meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix')
et.SubElement(meanImg, 'rows').text = '1'
et.SubElement(meanImg, 'cols').text = str(imgSize * imgSize * 3)
et.SubElement(meanImg, 'dt').text = 'f'
et.SubElement(meanImg, 'data').text = ' '.join(
['%e' % n for n in np.reshape(data, (imgSize * imgSize * 3))]
)
tree = et.ElementTree(root)
tree.write(fname)
x = xml.dom.minidom.parse(fname)
with open(fname, 'w') as f:
f.write(x.toprettyxml(indent=' '))
示例8: parse_map_xmltvsources_xml
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def parse_map_xmltvsources_xml(self):
"""Check for a mapping override file and parses it if found
"""
self._xmltv_sources_list = {}
mapping_file = self._get_mapping_file()
if mapping_file:
try:
tree = ET.ElementTree(file=mapping_file)
for group in tree.findall('.//xmltvextrasources/group'):
group_name = group.attrib.get('id')
urllist = []
for url in group:
urllist.append(url.text)
self._xmltv_sources_list[group_name] = urllist
except Exception, e:
msg = 'Corrupt override.xml file'
print(msg)
if DEBUG:
raise msg
示例9: saveMean
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def saveMean(fname, data):
root = et.Element('opencv_storage')
et.SubElement(root, 'Channel').text = '3'
et.SubElement(root, 'Row').text = str(IMGSIZE)
et.SubElement(root, 'Col').text = str(IMGSIZE)
meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix')
et.SubElement(meanImg, 'rows').text = '1'
et.SubElement(meanImg, 'cols').text = str(IMGSIZE * IMGSIZE * 3)
et.SubElement(meanImg, 'dt').text = 'f'
et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (IMGSIZE * IMGSIZE * 3))])
tree = et.ElementTree(root)
tree.write(fname)
x = xml.dom.minidom.parse(fname)
with open(fname, 'w') as f:
f.write(x.toprettyxml(indent = ' '))
示例10: isxmlorjson
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def isxmlorjson(s):
try:
json.loads(s)
isjson = True
except ValueError:
isjson = False
try:
ETree.ElementTree(ETree.fromstring(s))
isxml = True
except ETree.ParseError:
isxml = False
if isjson and isxml:
raise ValueError('This file appears to be both XML and JSON. I am ' +
'confused. Goodbye')
if isjson:
return 'json'
elif isxml:
return 'xml'
else:
return None
示例11: featuresToGPX
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def featuresToGPX(inputFC, outGPX, zerodate, pretty):
''' This is called by the __main__ if run from a tool or at the command line
'''
descInput = arcpy.Describe(inputFC)
if descInput.spatialReference.factoryCode != 4326:
arcpy.AddWarning("Input data is not projected in WGS84,"
" features were reprojected on the fly to create the GPX.")
generatePointsFromFeatures(inputFC , descInput, zerodate)
# Write the output GPX file
try:
if pretty:
gpxFile = open(outGPX, "w")
gpxFile.write(prettify(gpx))
else:
gpxFile = open(outGPX, "wb")
ET.ElementTree(gpx).write(gpxFile, encoding="UTF-8", xml_declaration=True)
except TypeError as e:
arcpy.AddError("Error serializing GPX into the file.")
finally:
gpxFile.close()
示例12: openDocument
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def openDocument(self,fileName):
self.clear()
# check whether file exists or not...
if not os.path.exists( fileName ):
print (u"fcDocumentReader: file {} does not exist!".format(fileName))
return
#
# decompress the file
f = zipfile.ZipFile(fileName,'r')
xml = f.read('Document.xml')
f.close()
#
# load the ElementTree
self.tree = ET.ElementTree(ET.fromstring(xml))
#
self.loadObjects()
示例13: collect_tripinfo
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def collect_tripinfo(self):
# read trip xml, has to be called externally to get complete file
trip_file = self.output_path + ('%s_%s_trip.xml' % (self.name, self.agent))
tree = ET.ElementTree(file=trip_file)
for child in tree.getroot():
cur_trip = child.attrib
cur_dict = {}
cur_dict['episode'] = self.cur_episode
cur_dict['id'] = cur_trip['id']
cur_dict['depart_sec'] = cur_trip['depart']
cur_dict['arrival_sec'] = cur_trip['arrival']
cur_dict['duration_sec'] = cur_trip['duration']
cur_dict['wait_step'] = cur_trip['waitingCount']
cur_dict['wait_sec'] = cur_trip['waitingTime']
self.trip_data.append(cur_dict)
# delete the current xml
cmd = 'rm ' + trip_file
subprocess.check_call(cmd, shell=True)
示例14: get_passphrase
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def get_passphrase(self, path):
xml_name = u'product-preferences.xml'
xml_file = None
if os.path.exists(os.path.join(path, xml_name)):
xml_file = os.path.join(path, xml_name)
else:
for p in os.listdir(path):
if p.startswith('system'):
new_directory = os.path.join(path, p)
for pp in os.listdir(new_directory):
if pp.startswith(u'o.sqldeveloper'):
if os.path.exists(os.path.join(new_directory, pp, xml_name)):
xml_file = os.path.join(new_directory, pp, xml_name)
break
if xml_file:
tree = ET.ElementTree(file=xml_file)
for elem in tree.iter():
if 'n' in elem.attrib.keys():
if elem.attrib['n'] == 'db.system.id':
return elem.attrib['v']
示例15: parseWindowsAliases
# 需要导入模块: from xml.etree import cElementTree [as 别名]
# 或者: from xml.etree.cElementTree import ElementTree [as 别名]
def parseWindowsAliases(self, aliases):
try:
with open(aliases) as xmlfile:
xmlroot = XML.ElementTree(file=xmlfile).getroot()
except (IOError, XMLParseError):
raise ValueError("Unable to open or read windows alias file: {}".format(aliases))
# Extract the mappings
try:
for elem in xmlroot.findall("./windowsZones/mapTimezones/mapZone"):
if elem.get("territory", "") == "001":
if elem.get("other") not in self.links:
self.links[elem.get("other")] = elem.get("type")
else:
print("Ignoring duplicate Windows alias: {}".format(elem.get("other")))
except (ValueError, KeyError):
raise ValueError("Unable to parse windows alias file: {}".format(aliases))