Python xml.dom.minidom.parse() Examples

The following are 30 code examples of xml.dom.minidom.parse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.dom.minidom , or try the search function .
Example #1
Source File: generate_repo.py    From repository.guilouz with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #2
Source File: tempest_results_processor.py    From JetPack with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: parse_svg.py    From pylustrator with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: parse_cvi42_xml.py    From ukbb_cardiac with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: remote.py    From andle with MIT License 6 votes vote down vote up
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 
Example #6
Source File: gtest_xml_output_unittest.py    From training_results_v0.5 with Apache License 2.0 6 votes vote down vote up
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() 
Example #7
Source File: anonymize_task_file.py    From gtg with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #8
Source File: parameters.py    From ddt4all with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #9
Source File: test_cli.py    From invoice2data with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: convert_model.py    From Generative-ConvACs with MIT License 6 votes vote down vote up
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 
Example #11
Source File: IDMapper.py    From DICAT with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #12
Source File: import_perltask.py    From anytask with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: xmlbehavior.py    From nyoka with Apache License 2.0 5 votes vote down vote up
def parseLiteral(inFileName):
    doc = minidom.parse(inFileName)
    rootNode = doc.childNodes[0]
    rootObj = xml_behavior.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    sys.stdout.write('from xmlbehavior import *\n\n')
    sys.stdout.write('rootObj = xml_behavior(\n')
    rootObj.exportLiteral(sys.stdout, 0)
    sys.stdout.write(')\n')
    return rootObj 
Example #14
Source File: pretty_vcproj.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def GetChildrenVsprops(filename):
  dom = parse(filename)
  if dom.documentElement.attributes:
    vsprops = dom.documentElement.getAttribute('InheritedPropertySheets')
    return FixFilenames(vsprops.split(';'), os.path.dirname(filename))
  return [] 
Example #15
Source File: gtest_xml_outfiles_test.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
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(wan@google.com): 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() 
Example #16
Source File: xmlbehavior_sub.py    From nyoka with Apache License 2.0 5 votes vote down vote up
def saxParse(inFileName):
    parser = make_parser()
    documentHandler = supermod.SaxXml_behaviorHandler()
    parser.setDocumentHandler(documentHandler)
    parser.parse('file:%s' % inFileName)
    rootObj = documentHandler.getRoot()
    #sys.stdout.write('<?xml version="1.0" ?>\n')
    #rootObj.export(sys.stdout, 0)
    return rootObj 
Example #17
Source File: test_minidom.py    From oss-ftp with MIT License 5 votes vote down vote up
def testUnlink(self):
        dom = parse(tstfile)
        dom.unlink() 
Example #18
Source File: test_minidom.py    From oss-ftp with MIT License 5 votes vote down vote up
def testNonZero(self):
        dom = parse(tstfile)
        self.confirm(dom)# should not be zero
        dom.appendChild(dom.createComment("foo"))
        self.confirm(not dom.childNodes[-1].childNodes)
        dom.unlink() 
Example #19
Source File: test_minidom.py    From oss-ftp with MIT License 5 votes vote down vote up
def testAppendChild(self):
        dom = parse(tstfile)
        dom.documentElement.appendChild(dom.createComment(u"Hello"))
        self.confirm(dom.documentElement.childNodes[-1].nodeName == "#comment")
        self.confirm(dom.documentElement.childNodes[-1].data == "Hello")
        dom.unlink() 
Example #20
Source File: test_minidom.py    From oss-ftp with MIT License 5 votes vote down vote up
def testGetElementsByTagName(self):
        dom = parse(tstfile)
        self.confirm(dom.getElementsByTagName("LI") == \
                dom.documentElement.getElementsByTagName("LI"))
        dom.unlink() 
Example #21
Source File: test_minidom.py    From oss-ftp with MIT License 5 votes vote down vote up
def testParseFromFile(self):
        dom = parse(StringIO(open(tstfile).read()))
        dom.unlink()
        self.confirm(isinstance(dom,Document)) 
Example #22
Source File: test_minidom.py    From BinderFilter with MIT License 5 votes vote down vote up
def testUnlink(self):
        dom = parse(tstfile)
        dom.unlink() 
Example #23
Source File: test_minidom.py    From BinderFilter with MIT License 5 votes vote down vote up
def testNonZero(self):
        dom = parse(tstfile)
        self.confirm(dom)# should not be zero
        dom.appendChild(dom.createComment("foo"))
        self.confirm(not dom.childNodes[-1].childNodes)
        dom.unlink() 
Example #24
Source File: test_minidom.py    From BinderFilter with MIT License 5 votes vote down vote up
def testAppendChild(self):
        dom = parse(tstfile)
        dom.documentElement.appendChild(dom.createComment(u"Hello"))
        self.confirm(dom.documentElement.childNodes[-1].nodeName == "#comment")
        self.confirm(dom.documentElement.childNodes[-1].data == "Hello")
        dom.unlink() 
Example #25
Source File: test_minidom.py    From BinderFilter with MIT License 5 votes vote down vote up
def testGetElementsByTagName(self):
        dom = parse(tstfile)
        self.confirm(dom.getElementsByTagName("LI") == \
                dom.documentElement.getElementsByTagName("LI"))
        dom.unlink() 
Example #26
Source File: xml.py    From pass-import with GNU General Public License v3.0 5 votes vote down vote up
def is_format(self):
        """Return True if the file is an XML file."""
        try:
            self.dom = parse(self.file)
        except (ParseError, ExpatError, UnicodeDecodeError):
            return False
        return True 
Example #27
Source File: xml.py    From pass-import with GNU General Public License v3.0 5 votes vote down vote up
def parse(self):
        """Parse HTML based file."""
        raise NotImplementedError()

    # Format recognition methods 
Example #28
Source File: test_minidom.py    From BinderFilter with MIT License 5 votes vote down vote up
def testParseFromFile(self):
        dom = parse(StringIO(open(tstfile).read()))
        dom.unlink()
        self.confirm(isinstance(dom,Document)) 
Example #29
Source File: core.py    From nzb-subliminal with GNU General Public License v3.0 5 votes vote down vote up
def load(self, stream, specs, ignore_element_types=None, ignore_element_names=None, max_level=None):
        """Load children :class:`Elements <Element>` with level lower or equal to the `max_level`
        from the `stream` according to the `specs`

        :param stream: file-like object from which to read
        :param dict specs: see :ref:`specs`
        :param int max_level: maximum level for children elements
        :param list ignore_element_types: list of element types to ignore
        :param list ignore_element_names: list of element names to ignore
        :param int max_level: maximum level of elements

        """
        self.data = parse(stream, specs, self.size, ignore_element_types, ignore_element_names, max_level) 
Example #30
Source File: __init__.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _parseSVNEntries_4(self, entriesFile):
        """
        Given a readable file object which represents a .svn/entries file in
        format version 4, return the revision as a string.  We do this by
        reading first XML element in the document that has a 'revision'
        attribute.
        """
        from xml.dom.minidom import parse
        doc = parse(entriesFile).documentElement
        for node in doc.childNodes:
            if hasattr(node, 'getAttribute'):
                rev = node.getAttribute('revision')
                if rev is not None:
                    return rev.encode('ascii')