Parse source.
@throws RequiredAttributeException
@throws XMLParsingException
173757
public function parse() {
		if($this->bParsed) {
			return;
		}

		if ($this->replacements) {
            // We cannot rely of html_entity_decode,
            // because it would replace &amp; and &lt; as well,
            // whereas we need to keep them unmodified.
            // We must do it manually, with a modified hardcopy
            // of PHP 5.4+ 's get_html_translation_table(ENT_XHTML)
            $this->source = XMLEntityTransformer::replace($this->source);
		}
		
		$this->xmlParser = xml_parser_create('UTF-8');
		xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, false);
		xml_set_object($this->xmlParser, $this);
		xml_set_element_handler($this->xmlParser, 'openTagHandler', 'closeTagHandler');
		xml_set_character_data_handler($this->xmlParser,'cdataHandler');

		//Prepare the detection of the very first tag, in order to compute
		//the offset in XML string as regarded by the parser.
		$this->firstOpening = true;

		try {
            $bSuccess = xml_parse($this->xmlParser, $this->source);
        } catch (RequiredAttributeException $ex) {
		    throw $ex->setFile($this->filename);
        }

        if ($bSuccess) {
            $errMsg = '';
            $lineNumber = 0;
        } else {
			$errMsg = xml_error_string(xml_get_error_code($this->xmlParser));
			$lineNumber = xml_get_current_line_number($this->xmlParser);
			if(count($this->stack)) {
				$lastElement = $this->stack[count($this->stack) - 1];
				if($lastElement instanceof ViewElementTag) {
					$errMsg .= '. Last element: ' . $lastElement->getTagName() . '(' . $lineNumber . ')';
				}
			}
		}

		xml_parser_free($this->xmlParser);
		$this->bParsed = $bSuccess;

		if(! $bSuccess ) {
			throw new XMLParsingException(
					$errMsg,
					$lineNumber);
		}

		// Store a serialized version of the parsed tree, if successfully parsed,
        // and if we've got a cache path.
        if ( ($this->cachePath) && ($this->filename !== null) && (! $this->unserialized) ) {
            $cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename, true);
            file_put_contents($cacheFile, serialize($this));
        }


    }
64748
protected function getTagAttributes()
    {
        $stream = $this->parser->getStream();
        $attributes = [];
        $lineno = $stream->getCurrent()->getLine();
        $name = $stream->getSourceContext()->getName();

        if (!$stream->test(Token::BLOCK_END_TYPE)) {
            do {
                $this->validateAttributeType($stream, 'name', ['NAME', 'STRING']);
                $attr = $stream->getCurrent()->getValue();
                $stream->next();
                $this->validateAttributeOperator($stream, $attr);
                $stream->next();
                $this->validateAttributeType($stream, 'value', ['NAME', 'STRING', 'NUMBER']);

                $attributes[$attr] = $this->parser->getExpressionParser()->parseExpression()->getAttribute('value');
            } while (!$stream->test(Token::BLOCK_END_TYPE));
        }

        return $this->formatAttributes($attributes, $lineno, $name);
    }
1109529
def parse(string)
      if string.blank?
        {}
      else
        @dbf = DocumentBuilderFactory.new_instance
        xml_string_reader = StringReader.new(string)
        xml_input_source = InputSource.new(xml_string_reader)
        doc = @dbf.new_document_builder.parse(xml_input_source)
        merge_element!({}, doc.document_element)
      end
    end
774911
public void parse(String xmlInput, boolean strict) throws ParseException {
		if (xmlInput == null) {
			throw new IllegalArgumentException("input can not be null");
		}
		ArrayList splitContents = split(xmlInput, interpreteAsXHTML, true);
		build(splitContents, interpreteAsXHTML);
	}
1026339
public function getAttributeSource()
    {
        $sources = array();
        foreach ($this->xml->xpath('//AdministrativeMetadata/Source/Party') as $party) {
            $sources[] = (string) $party['FormalName'];
        }

        return implode(', ', $sources);
    }
60807
public void parse() throws ResourceXMLParserException, IOException {
        final EntityResolver resolver = createEntityResolver();
        final SAXReader reader = new SAXReader(false);
        reader.setEntityResolver(resolver);

        try {

            final Document doc;
            if(null==this.doc){
                final InputStream in;
                if(null!=file){
                    in = new FileInputStream(file);
                }else{
                    in = input;
                }
                try{
                    doc=reader.read(in);
                }finally{
                    if(null!=file){
                        in.close();
                    }
                }
            }else{
                doc=this.doc;
            }

            final EntitySet set = new EntitySet();
            final Element root = doc.getRootElement();

            final List list = root.selectNodes(entityXpath);
            for (final Object n : list) {
                final Node node = (Node) n;
                final Entity ent = parseEnt(node, set);
                if (null != receiver) {
                    if (!receiver.resourceParsed(ent)) {
                        break;
                    }
                }
            }
            if (null != receiver) {
                receiver.resourcesParsed(set);
            }

        } catch (DocumentException e) {
            throw new ResourceXMLParserException(e);
        }
    }
475563
def _parse_attribute(
            self,
            element,  # type: ET.Element
            attribute,  # type: Text
            state  # type: _ProcessorState
    ):
        # type: (...) -> Any
        """"""
        parsed_value = self._default
        attribute_value = element.get(attribute, None)

        if attribute_value is not None:
            parsed_value = self._parser_func(attribute_value, state)
        elif self.required:
            state.raise_error(
                MissingValue, 'Missing required attribute "{}" on element "{}"'.format(
                    self._attribute, element.tag
                )
            )

        return parsed_value
858478
protected function parse(): void
    {
        // add the root node
        $this->root = new HtmlNode('root');
        $activeNode = $this->root;
        while ( ! is_null($activeNode)) {
            $str = $this->content->copyUntil('<');
            if ($str == '') {
                $info = $this->parseTag();
                if ( ! $info['status']) {
                    // we are done here
                    $activeNode = null;
                    continue;
                }

                // check if it was a closing tag
                if ($info['closing']) {
                    $foundOpeningTag  = true;
                    $originalNode     = $activeNode;
                    while ($activeNode->getTag()->name() != $info['tag']) {
                        $activeNode = $activeNode->getParent();
                        if (is_null($activeNode)) {
                            // we could not find opening tag
                            $activeNode = $originalNode;
                            $foundOpeningTag = false;
                            break;
                        }
                    }
                    if ($foundOpeningTag) {
                        $activeNode = $activeNode->getParent();
                    }
                    continue;
                }

                if ( ! isset($info['node'])) {
                    continue;
                }

                /** @var AbstractNode $node */
                $node = $info['node'];
                $activeNode->addChild($node);

                // check if node is self closing
                if ( ! $node->getTag()->isSelfClosing()) {
                    $activeNode = $node;
                }
            } else if ($this->options->whitespaceTextNode ||
                trim($str) != ''
            ) {
                // we found text we care about
                $textNode = new TextNode($str, $this->options->removeDoubleSpace);
                $activeNode->addChild($textNode);
            }
        }
    }
1177951
protected void parseAttribute(Token token) {
        // TODO this is a monster copy/paste - would be nicer to fix in the underlying library! :)
        token.setType(Type.ATTRIBUTE);

        parseName("attribute");

        if (pos == token.getStartOffset())
            throw new XMLParseException("Expected attribute name", source, pos);

        skipWhiteSpace();
        expect('=');
        skipWhiteSpace();

        char c = 0;
        if (pos < source.length())
            c = source.charAt(pos);
        if (c != '\'' && c != '"')
            throw new XMLParseException("Expected single or double quotes", source, pos);

        char endChar = c;
        boolean insideEntity = false;
        int errorPos = pos;

        while (true) {
            pos++;
            if (pos >= source.length()) {
                int i = Math.min(20, source.length() - token.getStartOffset());
                throw new XMLParseException("Missing end quote (" + endChar + ") of attribute: "
                        + lookAheadForErrorMessage(null, token.getStartOffset(), i), token);
            }

            c = source.charAt(pos);
            if (c == endChar)
                break;

            if (c == '<')
                throw new XMLParseException("Illegal character in attribute value: '" + c + "'", source, pos);

            if (c == '&') {
                insideEntity = true;
                errorPos = pos;
            } else if (c == ';') {
                verifyEntity(errorPos, pos + 1);
                insideEntity = false;
            } else {
                String msg = charValidator.isValid(source, pos);
                if (msg != null)
                    throw new XMLParseException("Illegal character found in attribute value. " + msg, source, pos);

                skipChar(c);
                pos--;
            }
        }

        if (insideEntity) {
            throw new XMLParseException("Missing ';' after '&': " + lookAheadForErrorMessage(null, errorPos, 20), source, errorPos);
        }

        // Skip end-char
        pos++;
    }
928745
public DataSources parse(XMLStreamReader reader) throws Exception
   {
      DataSources dataSources = null;

      //iterate over tags
      int iterate;
      try
      {
         iterate = reader.nextTag();
      }
      catch (XMLStreamException e)
      {
         //found a non tag..go on. Normally non-tag found at beginning are comments or DTD declaration
         iterate = reader.nextTag();
      }
      switch (iterate)
      {
         case END_ELEMENT : {
            // should mean we're done, so ignore it.
            break;
         }
         case START_ELEMENT : {

            switch (reader.getLocalName())
            {
               case XML.ELEMENT_DATASOURCES : {
                  dataSources = parseDataSources(reader);
                  break;
               }
               default :
                  throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
            }

            break;
         }
         default :
            throw new IllegalStateException();
      }

      return dataSources;

   }
954308
private void validate() {
        if (isValid != null) {
            return;
        }

        ParsingValidator v =
            new ParsingValidator(useSchema ? Languages.W3C_XML_SCHEMA_NS_URI
                                 : Languages.XML_DTD_NS_URI);
        List<Source> schemaSourceList = new ArrayList<Source>();
        if (systemId != null) {
            schemaSourceList.add(new StreamSource(systemId));
        }
        addSchemaSources(schemaSource, schemaSourceList);
        v.setSchemaSources(schemaSourceList.toArray(new Source[0]));

        try {
            ValidationResult r =
                v.validateInstance(new SAXSource(validationInputSource));
            isValid = r.isValid() ? Boolean.TRUE : Boolean.FALSE;
            for (ValidationProblem p : r.getProblems()) {
                validationProblem(p);
            }
        } catch (org.xmlunit.ConfigurationException e) {
            throw new ConfigurationException(e.getCause());
        } catch (org.xmlunit.XMLUnitException e) {
            throw new XMLUnitRuntimeException(e.getMessage(), e.getCause());
        }

        if (usingDoctypeReader && isValid == Boolean.FALSE) {
            try {
                messages.append("\nContent was: ")
                    .append(getOriginalContent(validationInputSource));
            } catch (IOException e) {
                // silent but deadly?
            }
        }
    }
584619
private List<JqassistantRules> readXmlSource(RuleSource ruleSource) {
        List<JqassistantRules> rules = new ArrayList<>();
        try (InputStream inputStream = ruleSource.getInputStream()) {
            JqassistantRules jqassistantRules = jaxbUnmarshaller.unmarshal(inputStream);
            rules.add(jqassistantRules);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read rules from '" + ruleSource.getId() + "'.", e);
        }
        return rules;
    }
670215
public function parseSourceAttributes()
    {
        $attributes = [];

        foreach ($this->translations as $translation)
        {
            $attributes[$translation->locale] = $translation->source->toArray();
        }

        return $attributes;
    }
238879
protected function parseData()
    {
        if (is_null($this->dataCache)) {
            $patternNamespace  = '(?P<namespace>[a-zA-Z0-9\\\\]+\\\\)?';
            $patternName       = '(?P<name>[a-zA-Z0-9]+)';
            $patternString     = '\"[^\"]*\"|\'[^\']*\'';
            $patternFloat      = '[0-9]+\.[0-9]+';
            $patternInt        = '[0-9]+';
            $patternBool       = 'true|false';
            $patternAttrValues = "({$patternString}|{$patternFloat}|{$patternInt}|{$patternBool})";
            $patternAttributes = "(?P<attr>\(\s*([a-zA-Z0-9]+\={$patternAttrValues}\s*\,?\s*)+\s*\))?";
            $pattern           = "^\@{$patternNamespace}{$patternName}\s*{$patternAttributes}(?P<rawtext>.*)$";
            
            if (preg_match("/{$pattern}/is", $this->getValue(), $matches)) {
                $this->dataCache = array(
                    'namespace'   => $matches['namespace'],
                    'name'        => $matches['name'],
                    'attributes'  => array(),
                    'tags'        => array(),
                );
                
                if (preg_match_all("/(?P<key>[a-zA-Z0-9]+)\s*\=\s*(?P<value>{$patternAttrValues})/is", $matches['attr'], $attributeMatches, PREG_SET_ORDER)) {
                    foreach ($attributeMatches as $attributeMatch) {
                        $key   = $attributeMatch['key'];
                        $value = $attributeMatch['value'];
                        switch(true){
                            case $value === 'true':
                                $value = true;
                                break;
                                
                            case $value === 'false':
                                $value = false;
                                break;
                                
                            case $value[0] === '"':
                            case $value[0] === "'":
                                $value = substr($value, 1, strlen($value)-2);
                                break;
                                
                            case strpos($value, '.')>0:
                                $value = (float)$value;
                                break;
                                
                            case is_numeric($value):
                                $value = (int)$value;
                                break;
                                
                        }
                        $this->dataCache['attributes'][$key] = $value;
                    }
                }
                
                foreach (preg_split("/\s+/is", trim($matches['rawtext'])) as $attributeTag) {
                    $this->dataCache['tags'][] = $attributeTag;
                }
            }
        }
        return $this->dataCache;
    }
475091
public static void parseCommonStoreAttributes(XMLExtendedStreamReader reader, StoreConfigurationBuilder builder, String attributeName, String value, int i) throws XMLStreamException {
      switch (Attribute.forName(attributeName)) {
         case FETCH_PERSISTENT_STATE:
            builder.fetchPersistentState(Boolean.valueOf(value));
            break;
         case IGNORE_MODIFICATIONS:
            builder.ignoreModifications(Boolean.valueOf(value));
            break;
         case PURGE_ON_STARTUP:
            builder.purgeOnStartup(Boolean.valueOf(value));
            break;
         case PRELOAD:
            builder.preload(Boolean.parseBoolean(value));
            break;
         case SHARED:
            builder.shared(Boolean.parseBoolean(value));
            break;
         default:
            throw ParseUtils.unexpectedAttribute(reader, i);
      }
   }
800660
private void parseAttribute(String name) throws Exception {
        String aname;
        String type;
        String value;
        int flags = LIT_ATTRIBUTE | LIT_ENTITY_REF;

        // Read the attribute name.
        aname = readNmtoken(true);
        type = getAttributeType(name, aname);

        // Parse '='
        parseEq();

        // Read the value, normalizing whitespace
        // unless it is CDATA.
        if (handler.stringInterning) {
            if ((type == "CDATA") || (type == null)) {
                value = readLiteral(flags);
            } else {
                value = readLiteral(flags | LIT_NORMALIZE);
            }
        } else {
            if ((type == null) || type.equals("CDATA")) {
                value = readLiteral(flags);
            } else {
                value = readLiteral(flags | LIT_NORMALIZE);
            }
        }

        // WFC: no duplicate attributes
        for (int i = 0; i < tagAttributePos; i++) {
            if (aname.equals(tagAttributes[i])) {
                fatal("duplicate attribute", aname, null);
            }
        }

        // Inform the handler about the
        // attribute.
        handler.attribute(aname, value, true);
        dataBufferPos = 0;

        // Note that the attribute has been
        // specified.
        if (tagAttributePos == tagAttributes.length) {
            String newAttrib[] = new String[tagAttributes.length * 2];
            System.arraycopy(tagAttributes, 0, newAttrib, 0, tagAttributePos);
            tagAttributes = newAttrib;
        }
        tagAttributes[tagAttributePos++] = aname;
    }
1133807
protected DataSource parseDataSource(XMLStreamReader reader) throws XMLStreamException, ParserException,
      ValidateException
   {
      String connectionUrl = null;
      String driverClass = null;
      String dataSourceClass = null;
      String driver = null;
      TransactionIsolation transactionIsolation = null;
      Map<String, String> connectionProperties = new HashMap<String, String>();
      Timeout timeoutSettings = null;
      DsSecurity securitySettings = null;
      Statement statementSettings = null;
      Validation validationSettings = null;
      String urlDelimiter = null;
      String urlSelectorStrategyClassName = null;
      String newConnectionSql = null;
      DsPool pool = null;

      //attributes reading
      String id = null;
      Boolean enabled = Defaults.ENABLED;
      String jndiName = null;
      Boolean spy = Defaults.SPY;
      Boolean useCcm = Defaults.USE_CCM;
      Boolean jta = Defaults.JTA;
      Boolean connectable = Defaults.CONNECTABLE;
      Boolean tracking = Defaults.TRACKING;

      Map<String, String> expressions = new HashMap<String, String>();

      for (int i = 0; i < reader.getAttributeCount(); i++)
      {
         switch (reader.getAttributeLocalName(i))
         {
            case XML.ATTRIBUTE_ENABLED : {
               enabled = attributeAsBoolean(reader, XML.ATTRIBUTE_ENABLED, Defaults.ENABLED, expressions);
               break;
            }
            case XML.ATTRIBUTE_JNDI_NAME : {
               jndiName = attributeAsString(reader, XML.ATTRIBUTE_JNDI_NAME, expressions);
               break;
            }
            case XML.ATTRIBUTE_ID : {
               id = attributeAsString(reader, XML.ATTRIBUTE_ID, expressions);
               break;
            }
            case XML.ATTRIBUTE_SPY : {
               spy = attributeAsBoolean(reader, XML.ATTRIBUTE_SPY, Defaults.SPY, expressions);
               break;
            }
            case XML.ATTRIBUTE_USE_CCM : {
               useCcm = attributeAsBoolean(reader, XML.ATTRIBUTE_USE_CCM, Defaults.USE_CCM, expressions);
               break;
            }
            case XML.ATTRIBUTE_JTA : {
               jta = attributeAsBoolean(reader, XML.ATTRIBUTE_JTA, Defaults.JTA, expressions);
               break;
            }
            case XML.ATTRIBUTE_CONNECTABLE : {
               connectable = attributeAsBoolean(reader, XML.ATTRIBUTE_CONNECTABLE, Defaults.CONNECTABLE, expressions);
               break;
            }
            case XML.ATTRIBUTE_TRACKING : {
               tracking = attributeAsBoolean(reader, XML.ATTRIBUTE_TRACKING, Defaults.TRACKING, expressions);
               break;
            }
            default :
               break;
         }
      }

      //elements reading
      while (reader.hasNext())
      {
         switch (reader.nextTag())
         {
            case END_ELEMENT : {
               if (XML.ELEMENT_DATASOURCE.equals(reader.getLocalName()))
               {
                  return new DataSourceImpl(connectionUrl, driverClass, dataSourceClass, driver, transactionIsolation,
                                            connectionProperties, timeoutSettings, securitySettings,
                                            statementSettings, validationSettings, urlDelimiter,
                                            urlSelectorStrategyClassName, newConnectionSql, id,
                                            enabled, jndiName, spy, useCcm, jta, connectable, tracking, pool,
                          !expressions.isEmpty() ? expressions : null);
               }
               else
               {
                  switch (reader.getLocalName())
                  {
                     case XML.ELEMENT_CONNECTION_PROPERTY :
                     case XML.ELEMENT_CONNECTION_URL :
                     case XML.ELEMENT_DRIVER_CLASS :
                     case XML.ELEMENT_DATASOURCE_CLASS :
                     case XML.ELEMENT_DRIVER :
                     case XML.ELEMENT_POOL :
                     case XML.ELEMENT_NEW_CONNECTION_SQL :
                     case XML.ELEMENT_URL_DELIMITER :
                     case XML.ELEMENT_URL_SELECTOR_STRATEGY_CLASS_NAME :
                     case XML.ELEMENT_TRANSACTION_ISOLATION :
                     case XML.ELEMENT_SECURITY :
                     case XML.ELEMENT_STATEMENT :
                     case XML.ELEMENT_TIMEOUT :
                     case XML.ELEMENT_VALIDATION :
                        break;
                     default :
                        throw new ParserException(bundle.unexpectedEndTag(reader.getLocalName()));
                  }
               }
               break;
            }
            case START_ELEMENT : {
               switch (reader.getLocalName())
               {
                  case XML.ELEMENT_CONNECTION_PROPERTY : {
                     parseConfigProperty(connectionProperties, reader, XML.ELEMENT_CONNECTION_PROPERTY, expressions);
                     break;
                  }
                  case XML.ELEMENT_CONNECTION_URL : {
                     connectionUrl = elementAsString(reader, XML.ELEMENT_CONNECTION_URL, expressions);
                     break;
                  }
                  case XML.ELEMENT_DRIVER_CLASS : {
                     driverClass = elementAsString(reader, XML.ELEMENT_DRIVER_CLASS, expressions);
                     break;
                  }
                  case XML.ELEMENT_DATASOURCE_CLASS : {
                     dataSourceClass = elementAsString(reader, XML.ELEMENT_DATASOURCE_CLASS, expressions);
                     break;
                  }
                  case XML.ELEMENT_DRIVER : {
                     driver = elementAsString(reader, XML.ELEMENT_DRIVER, expressions);
                     break;
                  }
                  case XML.ELEMENT_POOL : {
                     pool = parsePool(reader);
                     break;
                  }
                  case XML.ELEMENT_NEW_CONNECTION_SQL : {
                     newConnectionSql = elementAsString(reader, XML.ELEMENT_NEW_CONNECTION_SQL, expressions);
                     break;
                  }
                  case XML.ELEMENT_URL_DELIMITER : {
                     urlDelimiter = elementAsString(reader, XML.ELEMENT_URL_DELIMITER, expressions);
                     break;
                  }
                  case XML.ELEMENT_URL_SELECTOR_STRATEGY_CLASS_NAME : {
                     urlSelectorStrategyClassName = elementAsString(reader,
                                                                    XML.ELEMENT_URL_SELECTOR_STRATEGY_CLASS_NAME,
                                                                    expressions);
                     break;
                  }
                  case XML.ELEMENT_TRANSACTION_ISOLATION : {
                     String str = elementAsString(reader, XML.ELEMENT_TRANSACTION_ISOLATION, expressions);
                     transactionIsolation = TransactionIsolation.forName(str);
                     if (transactionIsolation == null)
                     {
                        transactionIsolation = TransactionIsolation.customLevel(str);
                     }
                     break;
                  }
                  case XML.ELEMENT_SECURITY : {
                     securitySettings = parseDsSecurity(reader);
                     break;
                  }
                  case XML.ELEMENT_STATEMENT : {
                     statementSettings = parseStatementSettings(reader);
                     break;
                  }
                  case XML.ELEMENT_TIMEOUT : {
                     timeoutSettings = parseTimeoutSettings(reader);
                     break;
                  }
                  case XML.ELEMENT_VALIDATION : {
                     validationSettings = parseValidationSetting(reader);
                     break;
                  }
                  default :
                     throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
               }
               break;
            }
         }
      }
      throw new ParserException(bundle.unexpectedEndOfDocument());
   }