本文整理汇总了Python中xml.dom.minidom.parse函数的典型用法代码示例。如果您正苦于以下问题:Python parse函数的具体用法?Python parse怎么用?Python parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: query
def query(self, token, langs=None):
''' makes a query and returns info (link, lang) about found subtitles'''
guessedData = self.guessFileData(token)
if "tvshow" != guessedData['type'] :
return []
elif langs and not set(langs).intersection((['en', 'nl'])): # lang is given but does not include nl or en
return []
if not langs :
availableLangs = ['nl', 'en']
else :
availableLangs = list(set(langs).intersection((['en', 'nl'])))
log.debug("possible langs : %s " % availableLangs)
sublinks = []
# Query the show to get the show id
showName = guessedData['name'].lower()
if exceptions.has_key(showName):
show_id = exceptions.get(showName)
elif self.cache['showids'].has_key(showName):
show_id = self.cache['showids'].get(showName)
else :
getShowId_url = "%sGetShowByName/%s" %(self.api, urllib.quote(showName))
log.debug("Looking for show Id @ %s" % getShowId_url)
page = urllib2.urlopen(getShowId_url)
dom = minidom.parse(page)
if not dom or len(dom.getElementsByTagName('showid')) == 0 :
page.close()
return []
show_id = dom.getElementsByTagName('showid')[0].firstChild.data
self.cache['showids'][showName] = show_id
f = open(self.cache_path, 'w')
pickle.dump(self.cache, f)
f.close()
page.close()
# Query the episode to get the subs
for lang in availableLangs :
getAllSubs_url = "%sGetAllSubsFor/%s/%s/%s/%s" %(self.api, show_id, guessedData['season'], guessedData['episode'], lang)
log.debug("Looking for subs @ %s" %getAllSubs_url)
page = urllib2.urlopen(getAllSubs_url)
dom = minidom.parse(page)
page.close()
for sub in dom.getElementsByTagName('result'):
release = sub.getElementsByTagName('filename')[0].firstChild.data
if release.endswith(".srt"):
release = release[:-4]
dllink = sub.getElementsByTagName('downloadlink')[0].firstChild.data
log.debug("Release found : %s" % release.lower())
log.debug("Searching for : %s" % token.lower())
if release.lower() == token.lower():
result = {}
result["release"] = release
result["link"] = dllink
result["page"] = dllink
result["lang"] = lang
sublinks.append(result)
return sublinks
示例2: test_output_compatible_setup_nooutput
def test_output_compatible_setup_nooutput(self):
tmpfile = tempfile.mktemp()
tmpfile2 = tempfile.mktemp()
os.chdir(basedir)
# Verify --silent can be supplied as app argument
cmd_line = ('./scripts/avocado --silent run --job-results-dir %s '
'--sysinfo=off --xunit %s --json %s passtest.py' %
(self.tmpdir, tmpfile, tmpfile2))
result = process.run(cmd_line, ignore_status=True)
output = result.stdout + result.stderr
expected_rc = exit_codes.AVOCADO_ALL_OK
try:
self.assertEqual(result.exit_status, expected_rc,
"Avocado did not return rc %d:\n%s" %
(expected_rc, result))
self.assertEqual(output, "", "Output is not empty:\n%s" % output)
# Check if we are producing valid outputs
with open(tmpfile2, 'r') as fp:
json_results = json.load(fp)
debug_log = json_results['debuglog']
self.check_output_files(debug_log)
minidom.parse(tmpfile)
finally:
try:
os.remove(tmpfile)
os.remove(tmpfile2)
except OSError:
pass
示例3: check_balloon
def check_balloon(logger,dom_name,dom_active,dom_eles):
"""
check balloon of given domain
"""
iDOM_XML = "/etc/libvirt/qemu/" + dom_name +".xml"
aDOM_XML = "/run/libvirt/qemu/" + dom_name +".xml"
if dom_active:
xml = minidom.parse(aDOM_XML)
dom = xml.getElementsByTagName('domain')[0]
mem_max = int(dom.getElementsByTagName('memory')[0]\
.childNodes[0].data)
mem_cur = int(dom.getElementsByTagName('currentMemory')[0]\
.childNodes[0].data)
logger.debug("Checking balloon.maximum: %d" \
% dom_eles.get("balloon.maximum"))
if not compare_value(logger,mem_max, \
dom_eles.get("balloon.maximum")):
return False
logger.debug("Checking balloon.current: %d" \
% dom_eles.get("balloon.current"))
if not compare_value(logger,mem_cur, \
dom_eles.get("balloon.current")):
return False
else:
xml = minidom.parse(iDOM_XML)
mem_max = int(xml.getElementsByTagName('memory')[0].\
childNodes[0].data)
logger.debug("Checking balloon.maximum: %d" \
% dom_eles.get("balloon.maximum"))
if not compare_value(logger,mem_max, \
dom_eles.get("balloon.maximum")):
return False
return True
示例4: _TestOutFile
def _TestOutFile(self, test_name, expected_xml):
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)
command = [gtest_prog_path, "--gtest_output=xml:%s" % self.output_dir_]
p = gtest_test_utils.Subprocess(command,
working_dir=gtest_test_utils.GetTempDir())
self.assert_(p.exited)
self.assertEquals(0, p.exit_code)
# TODO([email protected]): libtool causes the built test binary to be
# named lt-gtest_xml_outfiles_test_ instead of
# gtest_xml_outfiles_test_. To account for this possibility, we
# allow both names in the following code. We should remove this
# hack when Chandler Carruth's libtool replacement tool is ready.
output_file_name1 = test_name + ".xml"
output_file1 = os.path.join(self.output_dir_, output_file_name1)
output_file_name2 = 'lt-' + output_file_name1
output_file2 = os.path.join(self.output_dir_, output_file_name2)
self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),
output_file1)
expected = minidom.parseString(expected_xml)
if os.path.isfile(output_file1):
actual = minidom.parse(output_file1)
else:
actual = minidom.parse(output_file2)
self.NormalizeXml(actual.documentElement)
self.AssertEquivalentNodes(expected.documentElement,
actual.documentElement)
expected.unlink()
actual.unlink()
示例5: writeallrevinfo
def writeallrevinfo(playername, datestart, dateend):
filename2 = 'dumps/revdata_long/' + playername+"_"+str(datestart)[:-2]+'.xml'
count = 0
cont_flag = 1
uniqueid = str(datestart)[:-2]
urlstring = "rvstart="+str(dateend)[:-2]
while cont_flag>0:
if os.path.exists(filename2):
pass
else:
query = "http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvlimit=500&format=xml&rvprop=timestamp%7Cuser%7Csize%7Cflags&"+urlstring+"&rvend="+str(datestart)[:-2]+"&rvcontinue&titles="+playername
print "\n getting " + playername + "\n------------------------\n"
cur_page = urllib2.urlopen(query)
revdata = open(filename2,'w+')
revdata.write(cur_page.read())
revdata.close()
revdata = open(filename2,'r')
doc = minidom.parse(revdata)
rvcont = doc.getElementsByTagName("query-continue")
if len(rvcont)>0:
revisions = rvcont[0].getElementsByTagName("revisions")
rvstartid = revisions[0].getAttribute("rvstartid")
urlstring = "rvstartid=" + str(rvstartid)
uniqueid = rvstartid
cont_flag = 1
filename2 = 'dumps/revdata_long/' + playername+"_"+str(uniqueid)+'.xml'
else:
cont_flag = 0
cont_flag = 1
count = 0
uniqueid = str(datestart)[:-2]
while cont_flag>0:
filename2 = 'dumps/revdata_long/' + playername+"_"+str(uniqueid)+'.xml'
revdata = open(filename2,'r')
doc = minidom.parse(revdata)
count = count + len(doc.getElementsByTagName("rev"))
rvcont = doc.getElementsByTagName("query-continue")
if len(rvcont)>0:
revisions = rvcont[0].getElementsByTagName("revisions")
rvstartid = revisions[0].getAttribute("rvstartid")
urlstring = "rvstartid=" + str(rvstartid)
uniqueid = rvstartid
cont_flag = 1
else:
cont_flag = 0
return count
示例6: CheckDate
def CheckDate(self, context):
# Get the <created> time for the input file
root = minidom.parse(context.GetInputFilename()).documentElement
inputCreatedDate = ParseDate(GetXmlContent(FindXmlChild(root, "library_animations", "animation", "asset", "created")))
if inputCreatedDate == None:
context.Log("FAILED: Couldn't read <created> value from test input file.")
return None
# Get the output file
outputFilenames = context.GetStepOutputFilenames("Export")
if len(outputFilenames) == 0:
context.Log("FAILED: There are no export steps.")
return None
# Get the <created> time for the output file
root = minidom.parse(outputFilenames[0]).documentElement
outputCreatedDate = ParseDate(GetXmlContent(FindXmlChild(root, "library_animations", "animation", "asset", "created")))
if outputCreatedDate == None:
context.Log("FAILED: Couldn't read <created> value from the exported file.")
return None
if (outputCreatedDate - inputCreatedDate) != timedelta(0):
context.Log("FAILED: <created> is not preserved.")
context.Log("The original <created> time is " + str(inputCreatedDate))
context.Log("The exported <created> time is " + str(outputCreatedDate))
return False
context.Log("PASSED: <created> element is preserved.")
return True
示例7: __init__
def __init__(self):
file_handler_global = None
file_handler_user = None
xml_doc_global = None
xml_doc_user = None
self.__global_root_node = None
self.__user_root_node = None
self.__testcase_root_node = None
self.__global_config_filename = self.get_global_config_filename()
self.__user_config_filename = self.get_user_config_filename()
self.__testcase_config_filename = self.get_testcase_config_filename()
try:
file_handler_global = open(self.__global_config_filename, "r")
xml_doc_global = minidom.parse(file_handler_global)
self.__global_root_node = xml_doc_global.getElementsByTagName("config")[0]
except:
self.__global_root_node = None
try:
file_handler_user = open(self.__user_config_filename, "r")
xml_doc_user = minidom.parse(file_handler_user)
self.__user_root_node = xml_doc_user.getElementsByTagName("config")[0]
#print self.__user_root_node
except Exception, err:
#print Exception, err
self.__user_root_node = None
示例8: multiappend_dom
def multiappend_dom (sname, dname):
dom1 = parse(sname)
domr = parse(sname)
dom2 = parse(dname)
ref = ""
child_append = ""
lines_to_append = []
# busco el ref
for node in dom2.getElementsByTagName('cora:decorator'):
ref = node.getAttribute("ref")
print ref
# busco el append
for node in dom2.getElementsByTagName('cora:append'):
for child in node.childNodes:
s_append = child
xml_append = s_append.toxml()
if '<' in xml_append:
xml_append = xml_append.rstrip()
lines_to_append.append(s_append) #Guardo en esta lista las lineas a anexar
#Busco el index
index_r = 0
for i in range(0, len(domr.childNodes)):
index_ref = domr.childNodes[i]
if ref in index_ref.toxml():
index_r = i
break
# Los anexo
for i in range(0, len(lines_to_append)):
domr.childNodes[index_r].appendChild(lines_to_append[i])
print domr.toxml()
示例9: CheckDate
def CheckDate(self, context):
self.__assistant.CheckCrashes(context)
self.__assistant.CheckSteps(context, ["Import", "Export", "Validate"], [])
if not self.__assistant.GetResults(): return False
# Get the <created> time for the input file
root = minidom.parse(context.GetInputFilename()).documentElement
inputCreatedDate = ParseDate(GetXmlContent(FindXmlChild(root, "asset", "created")))
if inputCreatedDate == None:
context.Log("FAILED: Couldn't read <created> value from test input file.")
return False
# Get the output file
outputFilenames = context.GetStepOutputFilenames("Export")
if len(outputFilenames) == 0:
context.Log("FAILED: There are no export steps.")
return False
# Get the <created> time for the output file
root = minidom.parse(outputFilenames[0]).documentElement
outputCreatedDate = ParseDate(GetXmlContent(FindXmlChild(root, "asset", "created")))
if outputCreatedDate == None:
context.Log("FAILED: Couldn't read <created> value from the exported file.")
return False
if (outputCreatedDate - inputCreatedDate) < timedelta(0):
context.Log("FAILED: <created> has an incorrect time stamp. It should be later than the <created> value in the original file.")
context.Log("The original <created> time is " + str(inputCreatedDate))
context.Log("The exported <created> time is " + str(outputCreatedDate))
return False
context.Log("PASSED: <created> element is correct.")
return True
示例10: get_xml_data
def get_xml_data(self):
try:
xmlDoc = minidom.parse(self.name.replace("'", "") + ".xml")
except:
xmlDoc = minidom.parse("Wheaton College.xml")
building = xmlDoc.getElementsByTagName('building')
for card in building[0].getElementsByTagName('card'):
type_card = Card()
if card.attributes['type'].value == "spring_fling":
type_card.set_kind("spring_fling")
type_card.add_image(card.getElementsByTagName("image")[0].attributes['url'].value)
type_card.add_fact(card.getElementsByTagName("text")[0].childNodes[0].nodeValue)
elif card.attributes['type'].value == "secret_agent":
type_card.set_kind("secret_agent")
type_card.add_image(card.getElementsByTagName("image")[0].attributes['url'].value)
for text in card.getElementsByTagName("text"):
type_card.add_fact(text.childNodes[0].nodeValue)
elif card.attributes['type'].value =="paragraph":
type_card.set_kind("paragraph")
type_card.add_fact(card.getElementsByTagName("text")[0].childNodes[0].nodeValue)
elif card.attributes["type"].value == "modified_abe":
type_card.set_kind("modified_abe")
type_card.add_image(card.getElementsByTagName("image")[0].attributes['url'].value)
type_card.add_fact(card.getElementsByTagName("text")[0].childNodes[0].nodeValue)
else:
type_card.set_kind("err")
self.add_card(type_card)
示例11: do_check
def do_check(path):
iml_file = os.path.join(path, 'project.iml')
iml_dom = minidom.parse(iml_file)
found_paths = set()
for sourceFolder in self._get_sourceFolders(iml_dom):
url = sourceFolder.getAttribute('url')
source_path = re.sub(r'^.*/generated', 'generated', url)
found_paths.add(source_path)
self.assertIn("generated", found_paths)
self.assertIn("generated_tests", found_paths)
ipr_file = os.path.join(path, 'project.ipr')
ipr_dom = minidom.parse(ipr_file)
annotation_processing = self._get_compiler_configuration(ipr_dom).getElementsByTagName(
'annotationProcessing')[0]
profile = annotation_processing.getElementsByTagName('profile')[0]
self.assertEquals('True', profile.getAttribute('enabled'))
self.assertEquals('true', profile.getAttribute('default'))
self.assertEquals('Default', profile.getAttribute('name'))
processor_path = profile.getElementsByTagName('processorPath')[0]
self.assertEquals('true', processor_path.getAttribute('useClasspath'))
source_output_dir = profile.getElementsByTagName('sourceOutputDir')[0]
self.assertEquals('../../../generated', source_output_dir.getAttribute('name'))
source_test_output_dir = profile.getElementsByTagName('sourceTestOutputDir')[0]
self.assertEquals('../../../generated_tests', source_test_output_dir.getAttribute('name'))
found_processors = set()
for processor in profile.getElementsByTagName('processor'):
found_processors.add(processor.getAttribute('name'))
self.assertEquals({'com.google.auto.value.processor.AutoAnnotationProcessor',
'com.google.auto.value.processor.AutoValueBuilderProcessor',
'com.google.auto.value.processor.AutoValueProcessor'},
found_processors)
示例12: CheckDate
def CheckDate(self, context):
# Get the <modified> time for the input file
root = minidom.parse(context.GetInputFilename()).documentElement
inputDate = ParseDate(GetXmlContent(FindXmlChild(root, "library_visual_scenes", "visual_scene", "node", "asset", "modified")))
if inputDate == None:
context.Log("FAILED: Couldn't read <modified> value from test input file.")
return None
# Get the output file
outputFilenames = context.GetStepOutputFilenames("Export")
if len(outputFilenames) == 0:
context.Log("FAILED: There are no export steps.")
return None
# Get the <modified> time for the output file
root = minidom.parse(outputFilenames[0]).documentElement
outputDate = ParseDate(GetXmlContent(FindXmlChild(root, "library_visual_scenes", "visual_scene", "node", "asset", "modified")))
if outputDate == None:
context.Log("FAILED: Couldn't read <modified> value from the exported file.")
return None
# Modified data must be greater than or equal to original date to pass
if (outputDate - inputDate) < timedelta(0):
context.Log("FAILED: <modified> is not preserved.")
context.Log("The original <modified> time is " + str(inputDate))
context.Log("The exported <modified> time is " + str(outputDate))
return False
context.Log("PASSED: <modified> element is preserved or updated correctly.")
return True
示例13: inlineSchema
def inlineSchema(sourcePath,destinationPath):
"""Open sourcePath. For every included XSD, look for the document in the
current directory, and inline it. Write result to destinationPath."""
doc=xd.parse(sourcePath)
docElt=doc.documentElement
if not (docElt.nodeType==xd.Node.ELEMENT_NODE and docElt.tagName=="xs:schema"):
raise Exception, "file {0} doesn't start with an elt of name xs:schema".format(sourcePath)
inlined=set()
toInline=set()
findIncludes(docElt.firstChild,inlined,toInline)
while len(toInline):
incl=toInline.pop()
inclDoc=xd.parse(incl)
iDElt=inclDoc.documentElement
if not iDElt.nodeType==xd.Node.ELEMENT_NODE and iDElt.tagName=="xs:schema":
raise Exception, "file {0} doesn't start with an elt of name xs:schema".format(incl)
findIncludes(iDElt.firstChild,inlined,toInline)
for child in iDElt.childNodes:
docElt.appendChild(child.cloneNode(True))
inclDoc.unlink()
inlined.add(incl)
#print "added: {0}".format(incl)
destFile=codecs.open(destinationPath,'w','utf-8')
docElt.writexml(destFile)
destFile.close()
示例14: _load
def _load(self, filename):
zip = zipfile.ZipFile(filename, 'r')
zip.extractall(self.tmpdir)
wdoc = minidom.parse(zip.open('word/document.xml')).documentElement
wdoc.setAttribute('xmlns:wx', ns['wx'])
wdoc.setAttribute('xmlns:a', ns['a'])
self.body = wdoc.getElementsByTagName('w:body')[0]
relfile = zip.open('word/_rels/document.xml.rels')
for n in minidom.parse(relfile).getElementsByTagName('Relationship'):
self.media[n.getAttribute('Id')] = ( n.getAttribute('Target'),
n.getAttribute('Type') )
sdoc = minidom.parse(zip.open('word/styles.xml'))
for s in sdoc.getElementsByTagName('w:style'):
style_id = s.getAttribute('w:styleId')
n = s.getElementsByTagName('w:name')[0]
style_name = n.getAttribute('w:val')
self.styles[style_name] = style_id
try:
self.property = CustomProperty(self,
zip.open('docProps/custom.xml'))
except:
self.property = None
try:
self.settings = Settings(zip.open('word/settings.xml'))
except:
self.settings = None
try:
self.header = minidom.parse(zip.open('word/header1.xml'))
except:
self.header = None
try:
self.numberings = Numbering(zip.open('word/numbering.xml'))
except:
self.numberings = None
zip.close()
示例15: main
def main():
parser = OptionParser(conflict_handler="resolve")
parser.set_usage("mail-instance-creator.py <from-email-address> <to-email-address> <languagecode> <wikiaddress>\n\n\texample: mail-instance-creator.py '[email protected]' 'es' 'http://example.com/w/'")
(options, args) = parser.parse_args()
if len(args) != 4:
parser.error("mail-instance-creator.py expects exactly four arguments.")
fromaddress = args[0]
toaddress = args[1]
lang = args[2]
wikiaddress = args[3]
subjecturl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-subject/' + lang + '}}&format=xml'
bodyurl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-body/' + lang + '}}&format=xml'
dom = minidom.parse(urllib.urlopen(subjecturl))
subject = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
dom = minidom.parse(urllib.urlopen(bodyurl))
p = subprocess.Popen("ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub", shell=True, stdout=subprocess.PIPE)
fingerprint = p.communicate()[0]
fingerprint = fingerprint.split(' ')[1]
body = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
body = body + ' ' + gethostname() + ' (' + fingerprint + ')'
message = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (fromaddress, toaddress, subject, body)
p = subprocess.Popen("/usr/sbin/sendmail -t", shell=True, stdin=subprocess.PIPE)
p.communicate(message)
if p.wait() != 0:
return 1