本文整理汇总了Python中xml.dom.minidom.parse方法的典型用法代码示例。如果您正苦于以下问题:Python minidom.parse方法的具体用法?Python minidom.parse怎么用?Python minidom.parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.dom.minidom
的用法示例。
在下文中一共展示了minidom.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_result
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def _get_result(self, results_file):
"""Create Result namedtuple from file path
"""
short_name = os.path.basename(results_file)
dom = minidom.parse(results_file)
suite = dom.documentElement
errors = suite.getAttribute("errors")
failures = suite.getAttribute("failures")
num_tests = suite.getAttribute("tests")
time = suite.getAttribute("time")
test_cases = suite.getElementsByTagName("testcase")
test_map = self._list_to_map(test_cases)
result = Result(short_name, results_file, errors,
failures, num_tests,
time, test_map)
return result
示例2: parseContours
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def parseContours(node):
"""
Parse a Contours object. Each Contours object may contain several contours.
We first parse the contour name, then parse the points and pixel size.
"""
contours = {}
for child in keepElementNodes(node.childNodes):
contour_name = child.getAttribute('Hash:key')
sup = 1
for child2 in keepElementNodes(child.childNodes):
if child2.getAttribute('Hash:key') == 'Points':
points = []
for child3 in keepElementNodes(child2.childNodes):
x = float(child3.getElementsByTagName('Point:x')[0].firstChild.data)
y = float(child3.getElementsByTagName('Point:y')[0].firstChild.data)
points += [[x, y]]
if child2.getAttribute('Hash:key') == 'SubpixelResolution':
sub = int(child2.firstChild.data)
points = np.array(points)
points /= sub
contours[contour_name] = points
return contours
示例3: load
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def load(name, url=JCENTER_URL):
request = andle.http.request(
url + name.replace(".", "/").replace(":", "/") + "/maven-metadata.xml")
try:
DOMTree = minidom.parse(request)
collection = DOMTree.documentElement
versioning = collection.getElementsByTagName("versioning")[0]
latest = versioning.getElementsByTagName("release")[0]
version = latest.childNodes[0].data
return version
except BaseException:
if url == JCENTER_URL:
return load(name, GOOGLE_URL)
else:
print("fail to get version : " + name)
return None
示例4: LoadXML
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def LoadXML(self, file):
global xmlitemlist
global xmldoc
# empty the datatable and data dictionary before loading new file
self.datatable.delete(*self.datatable.get_children())
self.IDMap = {}
"""Parses the XML file and loads the data into the current window"""
try:
xmldoc = minidom.parse(file)
xmlitemlist = xmldoc.getElementsByTagName('Candidate')
for s in xmlitemlist:
identifier = s.getElementsByTagName("Identifier")[0].firstChild.nodeValue
realname = s.getElementsByTagName("RealName")[0].firstChild.nodeValue
dob = s.getElementsByTagName("DateOfBirth")[0].firstChild.nodeValue
self.AddIdentifierAction(identifier, realname, dob, False)
except:
pass
示例5: import_perltask
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def import_perltask(perltask_xml, year=None):
if year is None:
year = get_or_create_current_year()
course, created = Course.objects.get_or_create(year=year, name='Perltask')
if created:
print "WARNING: NEW Course created!"
course.type = Course.TYPE_POTOK
course.take_policy = Course.TAKE_POLICY_SELF_TAKEN
course.max_users_per_task = 8
course.max_days_without_score = 30
course.days_drop_from_blacklist = 14
course.save()
doc = parse(perltask_xml)
for task in doc.getElementsByTagName("task"):
if task.getAttribute('m'): # got_substasks
import_task_with_subtasks(task, course, year)
else:
import_task_no_subtasks(task, course, year)
示例6: _generate_zip_files
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def _generate_zip_files ( self ):
addons = os.listdir( "." )
# loop thru and add each addons addon.xml file
for addon in addons:
# create path
_path = os.path.join( addon, "addon.xml" )
#skip path if it has no addon.xml
if not os.path.isfile( _path ): continue
try:
# skip any file or .git folder
if ( not os.path.isdir( addon ) or addon == ".git" or addon == self.output_path or addon == self.tools_path): continue
# create path
_path = os.path.join( addon, "addon.xml" )
# split lines for stripping
document = minidom.parse(_path)
for parent in document.getElementsByTagName("addon"):
version = parent.getAttribute("version")
addonid = parent.getAttribute("id")
self._generate_zip_file(addon, version, addonid)
except Exception, e:
print e
示例7: convert_and_parse_xml
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def convert_and_parse_xml(src_model_fname):
dst_model_fname = os.path.basename(src_model_fname).split('.')[0] + '.xml.mdl'
with open(dst_model_fname, 'wb') as wfile:
wfile.write('<MODEL>\n')
with open(src_model_fname, 'rb') as rfile:
for line in rfile.readlines():
newline = line
if '<CNT>' in line:
newline = line.strip() + '</CNT>'
elif '<MEAN>' in line:
newline = line.strip() + '</MEAN>'
elif pn_re.findall(line):
newline = pn_re.sub(r'@ \2 \3 \4 \5 @',line)
wfile.write(newline.strip() + os.linesep)
wfile.write('</MODEL>\n')
xmldoc = minidom.parse(dst_model_fname)
os.remove(dst_model_fname)
return xmldoc
示例8: test_output_format_date_xml
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def test_output_format_date_xml(self):
pdf_files = get_sample_files('free_fiber.pdf')
test_file = 'test_compare.xml'
for pfile in pdf_files:
args = self.parser.parse_args(
['--output-name', test_file, '--output-format', 'xml', '--output-date-format', '%d/%m/%Y', pfile]
)
main(args)
with open(test_file) as xml_test_file:
xmldatatest = minidom.parse(xml_test_file)
dates = xmldatatest.getElementsByTagName('date')
compare_verified = (dates[0].firstChild.data == '02/07/2015')
print(compare_verified)
if not compare_verified:
self.assertTrue(False, 'Unexpected date format')
os.remove(test_file)
示例9: dumpAddressing
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def dumpAddressing():
xdom = xml.dom.minidom.parse("GenericAddressing.xml")
xdoc = xdom.documentElement
dict = {}
xml_funcs = getChildNodesByName(xdoc, u"Function")
for func in xml_funcs:
shortname = func.getAttribute(u"Name")
address = func.getAttribute(u"Address")
for name in getChildNodesByName(func, u"Name"):
longname = name.firstChild.nodeValue
dict[hex(int(address))[2:].upper()] = (shortname, longname)
break
js = json.dumps(dict)
f = open("json/addressing.json", "w")
f.write(js)
f.close()
示例10: parseStyleSheet
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def parseStyleSheet(text: str) -> list:
""" parse a style sheet text """
# remove line comments
text = re.sub("//.*?\n", "", text)
# remove multiline comments
text = text.replace("\n", " ")
text = re.sub("/\*.*?\*/", "", text)
text = re.sub("/\*.*?\*/", "", text)
style_definitions = []
styles = re.findall("[^}]*{[^}]*}", text)
for style in styles:
condition, main = style.split("{", 1)
parts = [part.strip().split(":", 1) for part in main[:-1].split(";") if part.strip() != ""]
style_dict = {k: v.strip() for k, v in parts}
for cond in condition.split(","):
style_definitions.append([cond.strip(), style_dict])
return style_definitions
示例11: main
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def main():
if len(sys.argv) > 1:
xmlfile = sys.argv[1]
else:
try:
data_dir = os.path.join(xdg_data_home, "gtg")
project_filepath = os.path.join(data_dir, "projects.xml")
dom = parse(project_filepath)
xmlproject = dom.getElementsByTagName("backend")[0]
xmlfile = str(xmlproject.getAttribute("path"))
xmlfile = os.path.join(data_dir, xmlfile)
print("Reading tasks from %s" % (xmlfile))
except:
print()
usage()
if len(sys.argv) > 2:
outputfile = sys.argv[2]
else:
# Use a reasonable default, and write out where it's sent
outputfile = "/tmp/gtg-tasks.xml"
print("Saving anonymized tasks to %s" % (outputfile))
anonymize(xmlfile, outputfile)
示例12: testTimestampValue
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def testTimestampValue(self):
"""Checks whether the timestamp attribute in the XML output is valid.
Runs a test program that generates an empty XML output, and checks if
the timestamp attribute in the testsuites tag is valid.
"""
actual = self._GetXmlOutput('gtest_no_test_unittest', [], {}, 0)
date_time_str = actual.documentElement.getAttributeNode('timestamp').value
# datetime.strptime() is only available in Python 2.5+ so we have to
# parse the expected datetime manually.
match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
self.assertTrue(
re.match,
'XML datettime string %s has incorrect format' % date_time_str)
date_time_from_xml = datetime.datetime(
year=int(match.group(1)), month=int(match.group(2)),
day=int(match.group(3)), hour=int(match.group(4)),
minute=int(match.group(5)), second=int(match.group(6)))
time_delta = abs(datetime.datetime.now() - date_time_from_xml)
# timestamp value should be near the current local time
self.assertTrue(time_delta < datetime.timedelta(seconds=600),
'time_delta is %s' % time_delta)
actual.unlink()
示例13: _getLeafNodeValueByPath
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def _getLeafNodeValueByPath(node, pathList, resultList, attrName, collectNodes = False):
"""
Parse a path in a xml document and return all corresponding entries.
"""
try:
if len(pathList) == 0:
if collectNodes:
resultList.append(node)
elif attrName != None:
if node.hasAttribute(attrName):
resultList.append(node.getAttribute(attrName))
else:
assert len(node.childNodes) == 1
resultList.append(node.childNodes[0].nodeValue)
else:
head = pathList[0]
tail = pathList[1:]
children = node.getElementsByTagName(head)
candidateChildList = []
for child in children:
if child.parentNode == node:
candidateChildList.append(child)
for child in candidateChildList:
_getLeafNodeValueByPath(child, list(tail), resultList, attrName, collectNodes)
except Exception:
sys.stderr.write('Cannot parse path: ' + str(pathList) + ' at node: ' + str(node) + '\n')
raise
示例14: LoadMap
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def LoadMap(self):
res = resources.Resources()
try:
win_zones = parse(res.GetResourceFileName(FLAGS.windows_zones_resource))
except resources.FileNotFound:
raise TimezoneError('Cannot load zone map from %s.' %
FLAGS.windows_zones_resource)
for zone in win_zones.getElementsByTagName('mapZone'):
self.zones[zone.getAttribute('type')] = zone.getAttribute('other')
示例15: load_addon_strings
# 需要导入模块: from xml.dom import minidom [as 别名]
# 或者: from xml.dom.minidom import parse [as 别名]
def load_addon_strings(addon, filename):
'''This is not an official XBMC method, it is here to faciliate
mocking up the other methods when running outside of XBMC.'''
def get_strings(fn):
xml = parse(fn)
strings = dict((tag.getAttribute('id'), tag.firstChild.data) for tag in xml.getElementsByTagName('string'))
#strings = {}
#for tag in xml.getElementsByTagName('string'):
#strings[tag.getAttribute('id')] = tag.firstChild.data
return strings
addon._strings = get_strings(filename)