本文整理汇总了Python中elementtree.ElementTree.ElementTree类的典型用法代码示例。如果您正苦于以下问题:Python ElementTree类的具体用法?Python ElementTree怎么用?Python ElementTree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ElementTree类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_authoreds
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)
示例2: __init__
def __init__(self, f):
self._artifacts = []
root = ElementTree().parse(f)
for artifact in root.find('artifacts'):
self._artifacts.append(Artifact(artifact))
示例3: scan_kid_files
def scan_kid_files(self, potfile, files):
messages = []
tags_to_ignore = ['script', 'style']
keys = []
kid_expr_re = re.compile(r"_\(('(?P<texta>[^']*)'|\"(?P<textb>[^\"]*)\")\)")
for fname in files:
print 'working on', fname
tree = None
try:
tree = ElementTree(file=fname).getroot()
except Exception, e:
print 'Skip %s: %s' % (fname, e)
continue
for el in tree.getiterator():
if self.options.loose_kid_support or el.get('lang', None):
tag = re.sub('({[^}]+})?(\w+)', '\\2', el.tag)
ents = []
if el.text: ents = [el.text.strip()]
if el.attrib: ents.extend(el.attrib.values())
for k in ents:
key = None
s = kid_expr_re.search(k)
if s:
key = s.groupdict()['texta'] or s.groupdict()['textb']
if key and (key not in keys) and (tag not in tags_to_ignore):
messages.append((tag, fname, key))
keys.append(key)
示例4: Write
def Write(self, outfile):
"""
Write the entity cache to an open file object.
"""
self.Fortify()
et = ElementTree(self.history.ToElement())
et.write(outfile)
示例5: requestMonitorId
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
示例6: install_xpi
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))
示例7: process_pom
def process_pom(self, config, pom_path):
doc = ElementTree(file=pom_path)
mc_version = ""
try:
mc_version = doc.findall('/{POM}properties/{POM}minecraft_version'.format(POM=POM_NS))[0].text
except:
mc_version = ""
config["minecraft_version"] = mc_version
示例8: createXmlFile
def createXmlFile(filePath, rootElement , version='1.0', encoding=ENCODING_IN ):
"""
Create an xml file
"""
doc = ElementTree(rootElement)
outfile = open(filePath, 'w')
outfile.write('<?xml version="' + version + '" encoding="' + encoding + '" ?>')
doc._write(outfile, doc._root, ENCODING_IN, {})
outfile.close()
示例9: process
def process(self, lang):
assert len(lang) == 2, 'Language name must be two letters long'
doc = ElementTree(file='%s.xml' % lang)
root = doc.getroot()
if root.tag == 'resources':
for child in root:
self.walk(child, (child.get('name'),), lang)
示例10: process
def process(self, lang):
assert len(lang) == 2, "Language name must be two letters long"
doc = ElementTree(file=os.path.join(self._dirname, "%s.xml" % lang))
root = doc.getroot()
if root.tag == "resources":
for child in root:
self.walk(child, (child.get("name"),), lang)
示例11: getpdisks
def getpdisks(controller="0"):
cmd = [ "omreport", "storage", "pdisk", "controller=" + controller, "-fmt", "xml" ]
(omstdin, omstdout) = popen2.popen2(cmd)
tree = ElementTree()
root = tree.parse(omstdin)
iter = root.getiterator()
pdisks = []
for element in iter:
if element.tag == "DCStorageObject":
pdisks.append(pdisk(element))
return pdisks
示例12: requestMonitorId
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
示例13: gettemp
def gettemp():
cmd = [ "omreport", "chassis", "temps", "-fmt", "xml" ]
(omstdin, omstdout) = popen2.popen2(cmd)
tree = ElementTree()
root = tree.parse(omstdin)
iter = root.getiterator()
sensors = []
for element in iter:
if element.tag == "TemperatureProbe":
sensors.append(tempprobe(element))
return sensors
示例14: PrintStats
def PrintStats():
"""Looks at the XML output and dumps render time."""
try:
from elementtree.ElementTree import ElementTree
except:
print "Unable to load ElementTree, skipping statistics."
else:
doc = ElementTree(file='stats.xml')
for timer in doc.findall('//timer'):
if "totaltime" == timer.get("name"):
print "Render time was %s seconds" % timer[0].text
break
示例15: get_dependencies
def get_dependencies(path):
dependencies = {}
doc = ElementTree(file=path)
deps = doc.findall('/%sdependencies' % POM_NS)
for dep in deps[0]:
groupId = dep.findall("%sgroupId" % POM_NS)[0].text
artifactId = dep.findall("%sartifactId" % POM_NS)[0].text
version = dep.findall("%sversion" % POM_NS)[0].text
path = ".".join([groupId, artifactId])
dependencies[path] = version
return dependencies