本文整理汇总了Python中elementtree.ElementTree.ElementTree.find方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.find方法的具体用法?Python ElementTree.find怎么用?Python ElementTree.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类elementtree.ElementTree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.find方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: requestMonitorId
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
def requestMonitorId(self,monitorTag):
xml = self._apiRequestXml(str('{0}/?apikey={1}&output={2}'+\
'&version={3}&action=getMonitors&tag={4}')\
.format(self.url,self.apiKey,self.output,self.version,monitorTag))
root = ElementTree(file=StringIO.StringIO(xml)).getroot()
monitor = root.find('./monitor/id') # Just the first matching monitor
# TODO handle multiple monitors with the same tag
# Dependent code assumes that exactly one is returned
if monitor is None:
raise Exception("No monitors matching " + monitorTag)
return root.find('./monitor/id').text
示例2: __init__
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
def __init__(self, f):
self._artifacts = []
root = ElementTree().parse(f)
for artifact in root.find('artifacts'):
self._artifacts.append(Artifact(artifact))
示例3: get_authoreds
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
def get_authoreds(researcher_object):
"""
Asks Symplectic API for info about specified researcher
Receives XML File as response
Parses XML File to find all publications for that researcher & notes
preferences they have for each publication
"""
# checking
# if not(researcher_object) or (researcher_object.symplectic_int_id is
# None): # int_id version
if not(researcher_object) or (researcher_object.symplectic_id is None):
# guid version
return
# symplectic api url and local file path
# url = SYMPLECTIC_API_URL + 'users/' +
# str(researcher_object.symplectic_int_id) # int_id version
url = "".join([
SYMPLECTIC_API_URL,
'users/',
str(researcher_object.symplectic_id)
])
# # tmp_filename = SYMPLECTIC_LOCAL_XML_FOLDER +
# SYMPLECTIC_LOCAL_AUTH_FOLDER +
# str(researcher_object.symplectic_int_id)
# + '.xml' # int_id version
tmp_filename = "".join([
SYMPLECTIC_LOCAL_XML_FOLDER,
SYMPLECTIC_LOCAL_AUTH_FOLDER,
str(researcher_object.symplectic_id),
'.xml'
])
# get xml document from symplectic api and store on hd
(tmp_filename, http_headers) = urllib.urlretrieve(url, tmp_filename)
# parse xml file
publications_etree = ElementTree(file=tmp_filename)
#delete local file from hd
#try:
os.remove(tmp_filename)
#except:
#pass
#publication elements are held in a subtree
publications_subtree = publications_etree.find(
SYMPLECTIC_NAMESPACE + 'publications'
)
# check if any publication elements in subtree
if publications_subtree is None or len(publications_subtree) < 1:
return
# now that we have their newest "i authored that pub" info, we can
# delete their old "i authored that pub" info
researcher_object.remove_all_authored()
# for each publication element in subtree
for publication_element in publications_subtree.getchildren():
_create_authored(publication_element, researcher_object)
示例4: requestMonitorId
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
def requestMonitorId(self,monitorTag):
req = urllib2.Request(str('{0}/?apikey={1}&output={2}'+\
'&version={3}&action=getMonitors&tag={4}')\
.format(self.url,self.apiKey,self.output,self.version,monitorTag))
res = urllib2.urlopen(req)
xml = res.read()
root = ElementTree(file=StringIO.StringIO(xml)).getroot()
return root.find('./monitor/id').text
示例5: install_xpi
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
def install_xpi(self, filename):
extract_path = os.path.join(self.profiledir, 'extensions', os.path.basename(filename))
os.makedirs(extract_path)
z = zipfile.ZipFile(filename, 'r')
z.extractall(extract_path)
doc = ElementTree(file = os.path.join(extract_path, 'install.rdf'))
eid = doc.find('.//{http://www.mozilla.org/2004/em-rdf#}id').text
os.rename(extract_path, os.path.join(os.path.dirname(extract_path), eid))
示例6: parse_file
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
def parse_file(self):
self.laps = []
self.position_start = None
self.date = None
self.time_start = None
self.time_end = None
self.track.trackfile.open()
xmltree = ElementTree(file=self.track.trackfile)
self.track.trackfile.close()
# take only first activity from file
xmlactivity = xmltree.find(self.TCX_NS + "Activities")[0]
lap_date = None
for xmllap in xmlactivity.findall(self.TCX_NS + "Lap"):
lap_date = dateutil.parser.parse(xmllap.get("StartTime"))
if self.date is None:
self.date = lap_date
time = int(float(xmllap.find(self.TCX_NS + "TotalTimeSeconds").text))
if xmllap.find(self.TCX_NS + "DistanceMeters") is None:
logging.debug("DistanceMeters not present in Lap data")
distance = None
else:
distance = str(float(xmllap.find(self.TCX_NS + "DistanceMeters").text) / 1000)
if xmllap.find(self.TCX_NS + "MaximumSpeed") is None:
logging.debug("MaximumSpeed is None")
speed_max = None
else:
logging.debug("MaximumSpeed xml is %r" % xmllap.find(self.TCX_NS + "MaximumSpeed"))
speed_max = str(float(xmllap.find(self.TCX_NS + "MaximumSpeed").text) * 3.6) # Given as meters per second in tcx file
logging.debug("speed_max is %s" % speed_max)
if xmllap.find(self.TCX_NS + "Calories") is not None:
calories = int(xmllap.find(self.TCX_NS + "Calories").text)
else:
calories = None
try:
hf_avg = int(xmllap.find(self.TCX_NS + "AverageHeartRateBpm").find(self.TCX_NS + "Value").text)
logging.debug("Found hf_avg: %s" % hf_avg)
except AttributeError:
hf_avg = None
logging.debug("Not found hf_avg")
try:
hf_max = int(xmllap.find(self.TCX_NS + "MaximumHeartRateBpm").find(self.TCX_NS + "Value").text)
logging.debug("Found hf_max: %s" % hf_max)
except AttributeError:
hf_max = None
logging.debug("Not found hf_max")
try:
cadence_avg = int(xmllap.find(self.TCX_NS + "Cadence").text)
logging.debug("Found average cadence: %s" % cadence_avg)
except AttributeError:
cadence_avg = None
logging.debug("Not found average cadence")
if time != 0 and distance is not None:
speed_avg = str(float(distance) * 3600 / time)
else:
speed_avg = None
cadence_max = None
elev_min = None
elev_max = None
elev_gain = None
elev_loss = None
last_elev = None
for xmltrack in xmllap.findall(self.TCX_NS + "Track"):
for xmltp in xmltrack.findall(self.TCX_NS + "Trackpoint"):
if not self.position_start:
xmlpos = xmltp.find(self.TCX_NS + "Position")
if xmlpos is not None:
if xmlpos.find(self.TCX_NS + "LatitudeDegrees") is not None and xmlpos.find(self.TCX_NS + "LongitudeDegrees") is not None:
lat = float(xmlpos.find(self.TCX_NS + "LatitudeDegrees").text)
lon = float(xmlpos.find(self.TCX_NS + "LongitudeDegrees").text)
self.position_start = (lat, lon)
if not self.time_start and xmltp.find(self.TCX_NS + "Time") is not None:
self.time_start = dateutil.parser.parse(xmltp.find(self.TCX_NS + "Time").text)
if xmltp.find(self.TCX_NS + "AltitudeMeters") is not None:
elev = int(round(float(xmltp.find(self.TCX_NS + "AltitudeMeters").text)))
else:
elev = last_elev
if elev != last_elev:
if elev_max is not None:
if elev > elev_max:
elev_max = elev
else:
elev_max = elev
if elev_min is not None:
if elev < elev_min:
elev_min = elev
else:
elev_min = elev
#.........这里部分代码省略.........
示例7: TCXFile
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
class TCXFile(ActivityFile):
filetypes = ["tcx"]
# TCX_NS="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
TCX_NS = "{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}"
xmlns = "{http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2}"
xmlactextns = "{http://www.garmin.com/xmlschemas/ActivityExtension/v2}"
xml_instance = "{http://www.w3.org/2001/XMLSchema-instance}"
def __init__(self, track, request=None):
ActivityFile.__init__(self, track, request)
track.trackfile.open()
self.xmltree = ElementTree(file=track.trackfile)
track.trackfile.close()
# logging.debug("Trackfile %r closed" % tcxfile.trackfile)
self.parse_trackpoints()
def parse_file(self):
self.laps = []
self.position_start = None
self.date = None
self.time_start = None
self.time_end = None
self.track.trackfile.open()
xmltree = ElementTree(file=self.track.trackfile)
self.track.trackfile.close()
# take only first activity from file
xmlactivity = xmltree.find(self.TCX_NS + "Activities")[0]
lap_date = None
for xmllap in xmlactivity.findall(self.TCX_NS + "Lap"):
lap_date = dateutil.parser.parse(xmllap.get("StartTime"))
if self.date is None:
self.date = lap_date
time = int(float(xmllap.find(self.TCX_NS + "TotalTimeSeconds").text))
if xmllap.find(self.TCX_NS + "DistanceMeters") is None:
logging.debug("DistanceMeters not present in Lap data")
distance = None
else:
distance = str(float(xmllap.find(self.TCX_NS + "DistanceMeters").text) / 1000)
if xmllap.find(self.TCX_NS + "MaximumSpeed") is None:
logging.debug("MaximumSpeed is None")
speed_max = None
else:
logging.debug("MaximumSpeed xml is %r" % xmllap.find(self.TCX_NS + "MaximumSpeed"))
speed_max = str(float(xmllap.find(self.TCX_NS + "MaximumSpeed").text) * 3.6) # Given as meters per second in tcx file
logging.debug("speed_max is %s" % speed_max)
if xmllap.find(self.TCX_NS + "Calories") is not None:
calories = int(xmllap.find(self.TCX_NS + "Calories").text)
else:
calories = None
try:
hf_avg = int(xmllap.find(self.TCX_NS + "AverageHeartRateBpm").find(self.TCX_NS + "Value").text)
logging.debug("Found hf_avg: %s" % hf_avg)
except AttributeError:
hf_avg = None
logging.debug("Not found hf_avg")
try:
hf_max = int(xmllap.find(self.TCX_NS + "MaximumHeartRateBpm").find(self.TCX_NS + "Value").text)
logging.debug("Found hf_max: %s" % hf_max)
except AttributeError:
hf_max = None
logging.debug("Not found hf_max")
try:
cadence_avg = int(xmllap.find(self.TCX_NS + "Cadence").text)
logging.debug("Found average cadence: %s" % cadence_avg)
except AttributeError:
cadence_avg = None
logging.debug("Not found average cadence")
if time != 0 and distance is not None:
speed_avg = str(float(distance) * 3600 / time)
else:
speed_avg = None
cadence_max = None
elev_min = None
elev_max = None
elev_gain = None
elev_loss = None
last_elev = None
for xmltrack in xmllap.findall(self.TCX_NS + "Track"):
for xmltp in xmltrack.findall(self.TCX_NS + "Trackpoint"):
if not self.position_start:
xmlpos = xmltp.find(self.TCX_NS + "Position")
if xmlpos is not None:
if xmlpos.find(self.TCX_NS + "LatitudeDegrees") is not None and xmlpos.find(self.TCX_NS + "LongitudeDegrees") is not None:
lat = float(xmlpos.find(self.TCX_NS + "LatitudeDegrees").text)
lon = float(xmlpos.find(self.TCX_NS + "LongitudeDegrees").text)
self.position_start = (lat, lon)
if not self.time_start and xmltp.find(self.TCX_NS + "Time") is not None:
self.time_start = dateutil.parser.parse(xmltp.find(self.TCX_NS + "Time").text)
#.........这里部分代码省略.........
示例8: len
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
if type == "float": type = "double"
if type == "": type = "int"
f.write("\t%s %s;\t// FlightGear property: %s\n" % (type,
chunk["name"], chunk["node"]))
f.write("\n\tunsigned int magic;\n};\n")
if __name__ == "__main__":
if len(sys.argv) != 3:
print "Usage: fgXMLtoHeader.py FG_OpenGC.xml output.h"
print "Copy output.h over ../Source/DataSources/FlightGear_Protocol.h"
sys.exit(1)
# Open the file, check it has the "PropertyList/generic/output"
root = ElementTree(file=sys.argv[1]).getroot()
if root == None or root.tag != "PropertyList":
print "File is not a property list"
sys.exit(1)
# Get the output section
output_sec = root.find("generic/output")
if output_sec == None:
print "File has no generic/output section"
sys.exit(1)
# Parse the file and write the result to a file
parse_tree = parse_file(output_sec, output_sec)
write_output(sys.argv[2], parse_tree)
示例9: exit
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
print "INVALID PROJECT DIRECTORY"
exit(0)
et = ElementTree()
#transform categories
print "Transforming Categories..."
for cat_fname in os.listdir(cat_path):
fpath = os.path.join(cat_path, cat_fname)
et.parse(fpath)
version = et.getroot().get("version")
if not version:
print "\tTransforming %s..." % cat_fname
root = Element("category",
{"version": "1.1",
"name": et.find("name").text.strip(),
"description": et.find("description").text.strip()})
et = ElementTree(root)
et.write(fpath, indent=True)
elif version == "1.0":
print "\tTransforming %s..." % cat_fname
root = Element("category",
{"version": "1.1",
"name": et.getroot().get("name"),
"description": et.getroot().get("description")})
et = ElementTree(root)
et.write(fpath, indent=True)
else:
print "\tSkipping %s - Not the version this script was written to transform." % cat_fname
#transform components
示例10: update_publication
# 需要导入模块: from elementtree.ElementTree import ElementTree [as 别名]
# 或者: from elementtree.ElementTree.ElementTree import find [as 别名]
def update_publication(publication_object):
"""
Asks Symplectic API for info about specified publication based upon
its guid
Receives XML File as response
Parses XML File to find publication info & all biblio-records for that
publication
"""
# checking
# print " update_publication", publication_object
if not(publication_object) or (publication_object.guid == ''):
return
# symplectic api url and local file path
url = SYMPLECTIC_API_URL + 'publications/' + publication_object.guid
tmp_filename = "".join([
SYMPLECTIC_LOCAL_XML_FOLDER,
SYMPLECTIC_LOCAL_PUBS_FOLDER,
str(publication_object.guid),
'.xml'
])
# get xml document from symplectic api and store on hd
(tmp_filename, http_headers) = urllib.urlretrieve(url, tmp_filename)
# parse xml file
pub_etree = ElementTree(file=tmp_filename)
#d elete local file from hd
# try:
os.remove(tmp_filename)
# except:
# pass
#++++++PUBLICATION++++++
# publication element
pub_element = pub_etree.getroot()
# no loading-of/blank publication object required as updating the one
# passed in
# check returned xml element is valid and for correct publication
if pub_element is None:
return
elif publication_object.guid != pub_element.get('id', ''):
return
# publication attributes
if pub_element is not None:
publication_object.new_id = pub_element.get('new-id')
if pub_element.get('is-deleted', 'false') == 'true':
publication_object.is_deleted = True
else:
publication_object.is_deleted = False
attr_names = ["type", "created-when", "last-modified-when"]
for attr_name in attr_names:
attr_value = pub_element.get(attr_name, "")
setattr(
publication_object,
attr_name.replace("-", "_"),
attr_value
)
# just fetched latest version from symplectic
publication_object.needs_refetch = False
# save updated publication object
publication_object.save()
# ++++++BIBLIOGRAPHIC-RECORD++++++
# bibliographic-record elements are held in a subtree
biblio_subtree = pub_etree.find(
SYMPLECTIC_NAMESPACE + 'bibliographic-records'
)
# check if any bibliographic-record elements in subtree
if biblio_subtree is None or len(biblio_subtree) < 1:
return
# for each bibliographic-record element in subtree
for biblio_element in biblio_subtree.getchildren():
_create_biblio_object(biblio_element, publication_object)