Parse the project.xml formatted file and fill in the nodes found
13377
public void parse() throws NodeFileParserException {
        final ResourceXMLParser resourceXMLParser;
        if(null!=file){
            resourceXMLParser=new ResourceXMLParser(file);
        }else{
            resourceXMLParser = new ResourceXMLParser(input);
        }
        //parse both node and settings
        resourceXMLParser.setReceiver(this);
//        long start = System.currentTimeMillis();
        try {
            resourceXMLParser.parse();
        } catch (ResourceXMLParserException e) {
            throw new NodeFileParserException(e);
        } catch (IOException e) {
            throw new NodeFileParserException(e);
        }
//        System.err.println("parse: " + (System.currentTimeMillis() - start));
    }
386499
def parsexml(self, node, ParentClass = None):
        """"""
        if (LXE and isinstance(node,ElementTree._ElementTree)) or (not LXE and isinstance(node, ElementTree.ElementTree)): #pylint: disable=protected-access
            node = node.getroot()
        elif isstring(node):
            node = xmltreefromstring(node).getroot()

        if node.tag.startswith('{' + NSFOLIA + '}'):
            foliatag = node.tag[nslen:]
            if foliatag == "FoLiA":
                if self.debug >= 1: print("[PyNLPl FoLiA DEBUG] Found FoLiA document",file=stderr)
                try:
                    self.id = node.attrib['{http://www.w3.org/XML/1998/namespace}id']
                except KeyError:
                    try:
                        self.id = node.attrib['XMLid']
                    except KeyError:
                        try:
                            self.id = node.attrib['id']
                        except KeyError:
                            raise Exception("FoLiA Document has no ID!")
                if 'version' in node.attrib:
                    self.version = node.attrib['version']
                    if checkversion(self.version) > 0:
                        print("WARNING!!! Document uses a newer version of FoLiA than this library! (" + self.version + " vs " + FOLIAVERSION + "). Any possible subsequent failures in parsing or processing may probably be attributed to this. Upgrade to foliapy (https://github.com/proycon/foliapy) to remedy this.",file=sys.stderr)
                else:
                    self.version = None

                if 'external' in node.attrib:
                    self.external = (node.attrib['external'] == 'yes')

                    if self.external and not self.parentdoc:
                        raise DeepValidationError("Document is marked as external and should not be loaded independently. However, no parentdoc= has been specified!")


                for subnode in node:
                    if subnode.tag == '{' + NSFOLIA + '}metadata':
                        self.parsemetadata(subnode)
                    elif (subnode.tag == '{' + NSFOLIA + '}text' or subnode.tag == '{' + NSFOLIA + '}speech') and self.mode == Mode.MEMORY:
                        if self.debug >= 1: print("[PyNLPl FoLiA DEBUG] Found Text",file=stderr)
                        e = self.parsexml(subnode)
                        if e is not None:
                            self.data.append(e)
            else:
                #generic handling (FoLiA)
                if not foliatag in XML2CLASS:
                    raise Exception("Unknown FoLiA XML tag: " + foliatag)
                Class = XML2CLASS[foliatag]
                return Class.parsexml(node,self)
        elif node.tag == '{' + NSDCOI + '}DCOI':
            if self.debug >= 1: print("[PyNLPl FoLiA DEBUG] Found DCOI document",file=stderr)
            self.autodeclare = True
            try:
                self.id = node.attrib['{http://www.w3.org/XML/1998/namespace}id']
            except KeyError:
                try:
                    self.id = node.attrib['id']
                except KeyError:
                    try:
                        self.id = node.attrib['XMLid']
                    except KeyError:
                        raise Exception("D-Coi Document has no ID!")
            for subnode in node:
                if subnode.tag == '{http://www.mpi.nl/IMDI/Schema/IMDI}METATRANSCRIPT':
                    self.metadatatype = MetaDataType.IMDI
                    self.setimdi(subnode)
                elif subnode.tag == '{' + NSDCOI + '}text':
                    if self.debug >= 1: print("[PyNLPl FoLiA DEBUG] Found Text",file=stderr)
                    e = self.parsexml(subnode)
                    if e is not None:
                        self.data.append( e )
        elif node.tag.startswith('{' + NSDCOI + '}'):
            #generic handling (D-Coi)
            if node.tag[nslendcoi:] in XML2CLASS:
                Class = XML2CLASS[node.tag[nslendcoi:]]
                return Class.parsexml(node,self)
            elif node.tag[nslendcoi:][0:3] == 'div': #support for div0, div1, etc:
                Class = Division
                return Class.parsexml(node,self)
            elif node.tag[nslendcoi:] == 'item': #support for listitem
                Class = ListItem
                return Class.parsexml(node,self)
            elif node.tag[nslendcoi:] == 'figDesc': #support for description in figures
                Class = Description
                return Class.parsexml(node,self)
            else:
                raise Exception("Unknown DCOI XML tag: " + node.tag)
        else:
            raise Exception("Unknown FoLiA XML tag: " + node.tag)

        self.pendingvalidation()
516090
def read_xml(filename):
    
    parser = et.XMLParser(remove_blank_text=True)
    isfile=False
    try:
        isfile = os.path.exists(filename)
    except ValueError as e:
        if 'path too long for Windows' in str(e):
            pass
        else:
            raise
    try:
        if isfile:
            return et.parse(filename, parser)
        else:
            r = et.fromstring(filename, parser)
            return r.getroottree()
    except IOError:
        log.exception('unable to open file [[}]'.format(filename))
    except et.XMLSyntaxError:
        log.exception('unable to parse XML [{}]'.format(filename))
        return None
    return None
1215473
public void parse() {
        ChunkHeader firstChunkHeader = readChunkHeader();
        if (firstChunkHeader == null) {
            return;
        }

        switch (firstChunkHeader.getChunkType()) {
            case ChunkType.XML:
            case ChunkType.NULL:
                break;
            case ChunkType.STRING_POOL:
            default:
                // strange chunk header type, just skip this chunk header?
        }

        // read string pool chunk
        ChunkHeader stringPoolChunkHeader = readChunkHeader();
        if (stringPoolChunkHeader == null) {
            return;
        }

        ParseUtils.checkChunkType(ChunkType.STRING_POOL, stringPoolChunkHeader.getChunkType());
        stringPool = ParseUtils.readStringPool(buffer, (StringPoolHeader) stringPoolChunkHeader);

        // read on chunk, check if it was an optional XMLResourceMap chunk
        ChunkHeader chunkHeader = readChunkHeader();
        if (chunkHeader == null) {
            return;
        }

        if (chunkHeader.getChunkType() == ChunkType.XML_RESOURCE_MAP) {
            long[] resourceIds = readXmlResourceMap((XmlResourceMapHeader) chunkHeader);
            resourceMap = new String[resourceIds.length];
            for (int i = 0; i < resourceIds.length; i++) {
                resourceMap[i] = Attribute.AttrIds.getString(resourceIds[i]);
            }
            chunkHeader = readChunkHeader();
        }

        while (chunkHeader != null) {
                /*if (chunkHeader.chunkType == ChunkType.XML_END_NAMESPACE) {
                    break;
                }*/
            long beginPos = buffer.position();
            switch (chunkHeader.getChunkType()) {
                case ChunkType.XML_END_NAMESPACE:
                    XmlNamespaceEndTag xmlNamespaceEndTag = readXmlNamespaceEndTag();
                    xmlStreamer.onNamespaceEnd(xmlNamespaceEndTag);
                    break;
                case ChunkType.XML_START_NAMESPACE:
                    XmlNamespaceStartTag namespaceStartTag = readXmlNamespaceStartTag();
                    xmlStreamer.onNamespaceStart(namespaceStartTag);
                    break;
                case ChunkType.XML_START_ELEMENT:
                    XmlNodeStartTag xmlNodeStartTag = readXmlNodeStartTag();
                    break;
                case ChunkType.XML_END_ELEMENT:
                    XmlNodeEndTag xmlNodeEndTag = readXmlNodeEndTag();
                    break;
                case ChunkType.XML_CDATA:
                    XmlCData xmlCData = readXmlCData();
                    break;
                default:
                    if (chunkHeader.getChunkType() >= ChunkType.XML_FIRST_CHUNK &&
                            chunkHeader.getChunkType() <= ChunkType.XML_LAST_CHUNK) {
                        Buffers.skip(buffer, chunkHeader.getBodySize());
                    } else {
                        throw new ParserException("Unexpected chunk type:" + chunkHeader.getChunkType());
                    }
            }
            Buffers.position(buffer, beginPos + chunkHeader.getBodySize());
            chunkHeader = readChunkHeader();
        }
    }
898189
def load_xml(self, filepath):
        """"""
        from os import path
        import xml.etree.ElementTree as ET
        #Make sure the file exists and then import it as XML and read the values out.
        uxpath = path.expanduser(filepath)
        if path.isfile(uxpath):
            tree = ET.parse(uxpath)
            vms("Parsing global settings from {}.".format(uxpath))
            root = tree.getroot()

            for child in root:
                if child.tag == "var":
                    self._vardict[child.attrib["name"]] = child.attrib["value"]
947149
def loadXml(self, xdata, filepath=''):
        
        # build options
        opts = {'platform': sys.platform}

        mkpath = lambda x: _mkpath(filepath, x, **opts)

        # lookup environment variables
        xenv = xdata.find('environment')
        if xenv is not None:
            env = {}
            log.info('loading environment...')
            for xkey in xenv:
                text = xkey.text
                if text:
                    env[xkey.tag] = os.path.expandvars(text)
                else:
                    env[xkey.tag] = ''

            self.setEnvironment(env)

        # lookup general settings
        xsettings = xdata.find('settings')
        if xsettings is not None:
            for xsetting in xsettings:
                key = xsetting.tag
                val = xsetting.text
                attr = '_' + key
                if hasattr(self, attr):
                    setattr(self, attr, val)

        # lookup options
        xoptions = xdata.find('options')
        if xoptions is not None:
            options = 0
            for xopt in xoptions:
                key = xopt.tag
                value = xopt.text

                if value.lower() == 'true':
                    try:
                        options |= Builder.Options[key]
                    except KeyError:
                        continue

            self._options = options

        # lookup path options
        xpaths = xdata.find('paths')
        if xpaths is not None:
            for xpath in xpaths:
                key = xpath.tag
                path = xpath.text

                if key.endswith('Paths'):
                    path = map(mkpath, path.split(';'))
                else:
                    path = mkpath(path)

                setattr(self, '_' + key, path)

        # lookup executable options
        xexe = xdata.find('executable')
        if xexe is not None:
            exe_tags = {'runtime': '_runtime',
                        'exe': '_executableName',
                        'cli': '_executableCliName',
                        'product': '_productName'}

            for tag, prop in exe_tags.items():
                xtag = xexe.find(tag)
                if xtag is not None:
                    value = xtag.text
                    if value.startswith('.'):
                        value = mkpath(value)

                    setattr(self, prop, value)

            # load exclude options
            xexcludes = xexe.find('excludes')
            if xexcludes is not None:
                excludes = []
                for xexclude in xexcludes:
                    excludes.append(xexclude.text)
                self.setExecutableExcludes(excludes)

            # load build data
            xexedata = xexe.find('data')
            if xexedata is not None:
                data = []
                for xentry in xexedata:
                    if xentry.tag == 'tree':
                        path = xentry.get('path', '')
                        if path:
                            path = mkpath(path)
                        else:
                            path = self.sourcePath()

                        prefix = xentry.get('prefix', os.path.basename(path))
                        excludes = xentry.get('excludes', '').split(';')

                        if excludes:
                            data.append(('tree', (path, prefix, excludes)))
                    else:
                        for xitem in xentry:
                            data.append((xentry.tag, xitem.attrs))

                self.setExecutableData(data)

            # load hidden imports
            xhiddenimports = xexe.find('hiddenimports')
            if xhiddenimports is not None:
                imports = []
                for ximport in xhiddenimports:
                    imports.append(ximport.text)
                self.setHiddenImports(imports)

            # load options
            xopts = xexe.find('options')
            if xopts is not None:
                for xopt in xopts:
                    if xopt.text.startswith('.'):
                        value = mkpath(xopt.text)
                    else:
                        value = xopt.text
                    self._executableOptions[xopt.tag] = value

        # lookup installer options
        xinstall = xdata.find('installer')
        if xinstall is not None:
            install_tags = {'name': '_installName'}

            for tag, prop in install_tags.items():
                xtag = xinstall.find(tag)
                if xtag is not None:
                    value = xtag.text
                    if value.startswith('.'):
                        value = mkpath(value)
                    setattr(self, prop, value)

            xopts = xinstall.find('options')
            if xopts is not None:
                for xopt in xopts:
                    if xopt.text.startswith('.'):
                        value = mkpath(xopt.text)
                    else:
                        value = xopt.text

                    self._installerOptions[xopt.tag] = value

            xdirectories = xinstall.find('additional_directories')
            if xdirectories is not None:
                for xdir in xdirectories:
                    self._installDirectories[xdir.get('path')] = xdir.get('source', '')
711574
function parse_files(files, options, callback) {
  var nodes = {
    // root section node
    '': {
      id: '',
      type: 'section',
      children: [],
      description: '',
      short_description: '',
      href: '#',
      root: true,
      file: '',
      line: 0
    }
  };

  var reportObject = { };
  
  async.forEachSeries(files, function (file, next_file) {
    var fn = parsers[path.extname(file)];

    if (!fn) {
      next_file();
      return;
    }

    console.info('Parsing file: ' + file);
    fn(file, options, function (err, file_nodes, file_report) {
      // TODO:  fail on name clash here as well -- as we might get name clash
      //        from different parsers, or even different files
      _.extend(nodes, file_nodes);
      _.extend(reportObject, file_report);
      next_file(err);
    });
  }, function (err) {
    callback(err, nodes, reportObject);
  });
}
937585
def _parse_nodes_section(f, current_section, nodes):
    
    section = {}
    dimensions = None

    if current_section == 'NODE_COORD_SECTION':
        dimensions = 3 # i: (i, j)
    elif current_section == 'DEMAND_SECTION':
        dimensions = 2 # i: q
    else:
        raise ParseException('Invalid section {}'.format(current_section))

    n = 0
    for line in f:
        line = strip(line)

        # Check dimensions
        definitions = re.split(r'\s*', line)
        if len(definitions) != dimensions:
            raise ParseException('Invalid dimensions from section {}. Expected: {}'.format(current_section, dimensions))

        node = int(definitions[0])
        values = [int(v) for v in definitions[1:]]

        if len(values) == 1:
            values = values[0]

        section[node] = values

        n = n + 1
        if n == nodes:
            break

    # Assert all nodes were read
    if n != nodes:
        raise ParseException('Missing {} nodes definition from section {}'.format(nodes - n, current_section))

    return section
385671
def parse
      properties_file = "#{OOXMLDocumentObject.path_to_folder}docProps/app.xml"
      unless File.exist?(properties_file)
        warn "There is no 'docProps/app.xml' in docx. It may be some problem with it"
        return self
      end
      node = parse_xml(properties_file)
      node.xpath('*').each do |node_child|
        case node_child.name
        when 'Properties'
          node_child.xpath('*').each do |node_child_child|
            case node_child_child.name
            when 'Pages'
              @pages = node_child_child.text.to_i
            when 'Words'
              @words = node_child_child.text.to_i
            end
          end
        end
      end
      self
    end
332167
def parseLines(self):
        """"""
        inAst = parse(''.join(self.lines), self.inFilename)
        # Visit all the nodes in our tree and apply Doxygen tags to the source.
        self.visit(inAst)
563729
private ProjectFile readFile(File file) throws MPXJException
   {
      try
      {
         String url = "jdbc:sqlite:" + file.getAbsolutePath();
         Properties props = new Properties();
         m_connection = org.sqlite.JDBC.createConnection(url, props);

         m_documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

         XPathFactory xPathfactory = XPathFactory.newInstance();
         XPath xpath = xPathfactory.newXPath();
         m_dayTimeIntervals = xpath.compile("/array/dayTimeInterval");
         m_entityMap = new HashMap<String, Integer>();
         return read();
      }

      catch (Exception ex)
      {
         throw new MPXJException(MPXJException.INVALID_FORMAT, ex);
      }

      finally
      {
         if (m_connection != null)
         {
            try
            {
               m_connection.close();
            }

            catch (SQLException ex)
            {
               // silently ignore exceptions when closing connection
            }
         }

         m_documentBuilder = null;
         m_dayTimeIntervals = null;
         m_entityMap = null;
      }
   }
1094171
def parse_fast(xmlfile, element_name, attrnames, warn=False, optional=False):
    
    prefixedAttrnames = [_prefix_keyword(a, warn) for a in attrnames]
    if optional:
        pattern = ''.join(['<%s' % element_name] +
                          ['(\\s+%s="(?P<%s>[^"]*?)")?' % a for a in zip(attrnames, prefixedAttrnames)])
    else:
        pattern = '.*'.join(['<%s' % element_name] +
                            ['%s="([^"]*)"' % attr for attr in attrnames])
    Record = namedtuple(element_name, prefixedAttrnames)
    reprog = re.compile(pattern)
    for line in open(xmlfile):
        m = reprog.search(line)
        if m:
            if optional:
                yield Record(**m.groupdict())
            else:
                yield Record(*m.groups())
927332
def parse(self, file):
        '''
        
        '''
        parser = make_parser()
        self.clear()

        class Extractor(xml.sax.ContentHandler):

            def __init__(self, parent):
                self.parent = parent

            def startElement(self, name, attrs):
                attribs = {}
                for attrname in attrs.getNames():
                    attrvalue = attrs.get(attrname)
                    attribs[attrname] = attrvalue
                self.parent.StartTag(name, attribs)

            def characters(self, text):
                self.parent.NewData(text)

            def endElement(self, name):
                self.parent.EndTag(name)
        parser.setContentHandler(Extractor(self))
        # OFFLINE MODE
        parser.setFeature(handler.feature_external_ges, False)
        fob = open(file, 'r')
        parser.parse(fob)
        return self.piece
210669
def parse(self):
        """"""
        result = nodes.Template(self.subparse(), lineno=1)
        result.set_environment(self.environment)
        return result
249019
def _parse_docstrings(self, filepath):
        """"""        
        xmlpath = self.get_xmldoc_path(filepath)
        if self.tramp.exists(xmlpath):
            xmlstring = self.tramp.read(xmlpath)
            self.modulep.docparser.parsexml(xmlstring, self.modules, xmlpath)
121582
def process_xml(self, xml):
        '''
        
        '''
        root = objectify.fromstring(xml, parser = etree.XMLParser())
        # Parse all children of the root node
        for child in root.getchildren():
            if 'title' in child.tag:
                self.title = child.text
            if 'description' in child.tag:
                self.description = child.text
            if 'secure_launch_url' in child.tag:
                self.secure_launch_url = child.text
            elif 'launch_url' in child.tag:
                self.launch_url = child.text
            if 'icon' in child.tag:
                self.icon = child.text
            if 'secure_icon' in child.tag:
                self.secure_icon = child.text
            if 'cartridge_bundle' in child.tag:
                self.cartridge_bundle = child.attrib['identifierref']
            if 'catridge_icon' in child.tag:
                self.cartridge_icon = child.atrib['identifierref']

            if 'vendor' in child.tag:
                # Parse vendor tag
                for v_child in child.getchildren():
                    if 'code' in v_child.tag:
                        self.vendor_code = v_child.text
                    if 'description' in v_child.tag:
                        self.vendor_description = v_child.text
                    if 'name' in v_child.tag:
                        self.vendor_name = v_child.text
                    if 'url' in v_child.tag:
                        self.vendor_url = v_child.text
                    if 'contact' in v_child.tag:
                        # Parse contact tag for email and name
                        for c_child in v_child:
                            if 'name' in c_child.tag:
                                self.vendor_contact_name = c_child.text
                            if 'email' in c_child.tag:
                                self.vendor_contact_email = c_child.text

            if 'custom' in child.tag:
                # Parse custom tags
                for custom_child in child.getchildren():
                    self.custom_params[custom_child.attrib['name']] =\
                            custom_child.text

            if 'extensions' in child.tag:
                platform = child.attrib['platform']
                properties = {}

                # Parse extension tags
                for ext_child in child.getchildren():
                    if 'property' in ext_child.tag:
                        properties[ext_child.attrib['name']] = ext_child.text
                    elif 'options' in ext_child.tag:
                        opt_name = ext_child.attrib['name']
                        options = {}
                        for option_child in ext_child.getchildren():
                            options[option_child.attrib['name']] =\
                                    option_child.text
                        properties[opt_name] = options

                self.set_ext_params(platform, properties)
95326
function parsePlistXML (node) {
  var i, new_obj, key, val, new_arr, res, d;

  if (!node)
    return null;

  if (node.nodeName === 'plist') {
    new_arr = [];
    for (i=0; i < node.childNodes.length; i++) {
      // ignore comment nodes (text)
      if (!shouldIgnoreNode(node.childNodes[i])) {
        new_arr.push( parsePlistXML(node.childNodes[i]));
      }
    }
    return new_arr;

  } else if (node.nodeName === 'dict') {
    new_obj = {};
    key = null;
    for (i=0; i < node.childNodes.length; i++) {
      // ignore comment nodes (text)
      if (!shouldIgnoreNode(node.childNodes[i])) {
        if (key === null) {
          key = parsePlistXML(node.childNodes[i]);
        } else {
          new_obj[key] = parsePlistXML(node.childNodes[i]);
          key = null;
        }
      }
    }
    return new_obj;

  } else if (node.nodeName === 'array') {
    new_arr = [];
    for (i=0; i < node.childNodes.length; i++) {
      // ignore comment nodes (text)
      if (!shouldIgnoreNode(node.childNodes[i])) {
        res = parsePlistXML(node.childNodes[i]);
        if (null != res) new_arr.push(res);
      }
    }
    return new_arr;

  } else if (node.nodeName === '#text') {
    // TODO: what should we do with text types? (CDATA sections)

  } else if (node.nodeName === 'key') {
    return node.childNodes[0].nodeValue;

  } else if (node.nodeName === 'string') {
    res = '';
    for (d=0; d < node.childNodes.length; d++) {
      res += node.childNodes[d].nodeValue;
    }
    return res;

  } else if (node.nodeName === 'integer') {
    // parse as base 10 integer
    return parseInt(node.childNodes[0].nodeValue, 10);

  } else if (node.nodeName === 'real') {
    res = '';
    for (d=0; d < node.childNodes.length; d++) {
      if (node.childNodes[d].nodeType === 3) {
        res += node.childNodes[d].nodeValue;
      }
    }
    return parseFloat(res);

  } else if (node.nodeName === 'data') {
    res = '';
    for (d=0; d < node.childNodes.length; d++) {
      if (node.childNodes[d].nodeType === 3) {
        res += node.childNodes[d].nodeValue.replace(/\s+/g, '');
      }
    }

    // decode base64 data to a Buffer instance
    return new Buffer(res, 'base64');

  } else if (node.nodeName === 'date') {
    return new Date(node.childNodes[0].nodeValue);

  } else if (node.nodeName === 'true') {
    return true;

  } else if (node.nodeName === 'false') {
    return false;
  }
}