// If on attribute, moves to the element that contains the attribute node public override bool MoveToElement() { if (!_coreReader.MoveToElement()) { return(false); } _parsingFunction = ParsingFunction.Read; return(true); }
// Moves to the next attribute of the current node public override bool MoveToNextAttribute() { if (!_coreReader.MoveToNextAttribute()) { return(false); } _parsingFunction = ParsingFunction.Read; return(true); }
// Moves to an attribute with the specified LocalName and NamespceURI public override bool MoveToAttribute(string localName, string namespaceURI) { if (!_coreReader.MoveToAttribute(localName, namespaceURI)) { return(false); } _parsingFunction = ParsingFunction.Read; return(true); }
// Moves to an attribute with the specified Name public override bool MoveToAttribute(string name) { if (!_coreReader.MoveToAttribute(name)) { return(false); } _parsingFunction = ParsingFunction.Read; return(true); }
public bool ParseResponse(string responseText, ParsingFunction parsingFunction) { try{ response = parsingFunction(responseText); return(true); }catch (Exception e) { // Parsing error this.errorLog = "Couldn't parse response from server: " + e.Message + "\nResponse from server: \n" + request.text; return(false); } }
public ServerTransaction(string url, ParsingFunction parsingFunction) { if (RequestIsCached(url)) { ParseResponse(File.ReadAllText(URLToFilePath(url)), parsingFunction); } else { request = new WWW(url); } }
internal XmlValidatingReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext context) : this(new XmlTextReader(xmlFragment, fragType, context)) { if (this.coreReader.BaseURI.Length > 0) { this.validator.BaseUri = this.GetResolver().ResolveUri(null, this.coreReader.BaseURI); } if (context != null) { this.parsingFunction = ParsingFunction.ParseDtdFromContext; this.parserContext = context; } }
// Reads and validated next node from the input data public override bool Read() { switch (parsingFunction) { case ParsingFunction.Read: if (coreReader.Read()) { ProcessCoreReaderEvent(); return(true); } else { validator.CompleteValidation(); return(false); } case ParsingFunction.ParseDtdFromContext: parsingFunction = ParsingFunction.Read; ParseDtdFromParserContext(); goto case ParsingFunction.Read; case ParsingFunction.Error: case ParsingFunction.ReaderClosed: return(false); case ParsingFunction.Init: parsingFunction = ParsingFunction.Read; // this changes the value returned by ReadState if (coreReader.ReadState == ReadState.Interactive) { ProcessCoreReaderEvent(); return(true); } else { goto case ParsingFunction.Read; } case ParsingFunction.ResolveEntityInternally: parsingFunction = ParsingFunction.Read; ResolveEntityInternally(); goto case ParsingFunction.Read; case ParsingFunction.InReadBinaryContent: parsingFunction = ParsingFunction.Read; readBinaryHelper.Finish(); goto case ParsingFunction.Read; default: Debug.Assert(false); return(false); } }
// Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified stream, fragment type and parser context // This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader // SxS: This method resolves an Uri but does not expose it to the caller. It's OK to suppress the SxS warning. internal XmlValidatingReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext?context) : this(new XmlTextReader(xmlFragment, fragType, context)) { if (_coreReader.BaseURI !.Length > 0) { _validator.BaseUri = GetResolver() !.ResolveUri(null, _coreReader.BaseURI); } if (context != null) { _parsingFunction = ParsingFunction.ParseDtdFromContext; _parserContext = context; } }
// Iterates through the current attribute value's text and entity references chunks. public override bool ReadAttributeValue() { if (parsingFunction == ParsingFunction.InReadBinaryContent) { parsingFunction = ParsingFunction.Read; readBinaryHelper.Finish(); } if (!coreReader.ReadAttributeValue()) { return(false); } parsingFunction = ParsingFunction.Read; return(true); }
SplitList(ParsingFunction parsingFunction) { List <string> names = new List <string>(); List <double> values = new List <double>(); List <ParsedTables> pt = parsingFunction(); for (int i = 0; i < pt.Count; i++) { names.Add(pt[i].Name); values.Add(pt[i].GetCacheSpending()); } return(names, values); }
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { if (this.ReadState != System.Xml.ReadState.Interactive) { return(0); } if (this.parsingFunction != ParsingFunction.InReadBinaryContent) { this.readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(this.readBinaryHelper, this.outerReader); } this.parsingFunction = ParsingFunction.Read; int num = this.readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count); this.parsingFunction = ParsingFunction.InReadBinaryContent; return(num); }
public override bool Read() { switch (this.parsingFunction) { case ParsingFunction.Read: break; case ParsingFunction.Init: this.parsingFunction = ParsingFunction.Read; if (this.coreReader.ReadState != System.Xml.ReadState.Interactive) { break; } this.ProcessCoreReaderEvent(); return(true); case ParsingFunction.ParseDtdFromContext: this.parsingFunction = ParsingFunction.Read; this.ParseDtdFromParserContext(); break; case ParsingFunction.ResolveEntityInternally: this.parsingFunction = ParsingFunction.Read; this.ResolveEntityInternally(); break; case ParsingFunction.InReadBinaryContent: this.parsingFunction = ParsingFunction.Read; this.readBinaryHelper.Finish(); break; case ParsingFunction.ReaderClosed: case ParsingFunction.Error: return(false); default: return(false); } if (this.coreReader.Read()) { this.ProcessCoreReaderEvent(); return(true); } this.validator.CompleteValidation(); return(false); }
internal static List <IParsingResult> ParseList(ParsingFunction parse, ParsingContext context) { List <IParsingResult> results = new List <IParsingResult>(); while (true) { IParsingResult result = parse(context); if (result == null) { break; } results.Add(result); } return(results); }
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return(0); } // init ReadChunkHelper when called first time if (parsingFunction != ParsingFunction.InReadBinaryContent) { readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(readBinaryHelper, outerReader); } // set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper parsingFunction = ParsingFunction.Read; // call to the helper int readCount = readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count); // setup parsingFunction parsingFunction = ParsingFunction.InReadBinaryContent; return(readCount); }
public RequestStatus Update(ParsingFunction ParseResponse) { RequestStatus requestStatus = GetRequestStatus(); if (requestStatus == RequestStatus.DOWNLOADING) { if (request.isDone) { if (request.error == null) { if (this.ParseResponse(request.text, ParseResponse)) { // Cache the result File.WriteAllText(URLToFilePath(request.url), request.text); return(RequestStatus.OK); } else { return(RequestStatus.ERROR); } } else { // Connection error this.errorLog = "Couldn't get info from server: " + request.error; return(RequestStatus.ERROR); } } return(RequestStatus.DOWNLOADING); } else { // Status other than "downloading" remain the same when updating. return(requestStatus); } }
internal void Close(bool closeStream) { coreReaderImpl.Close(closeStream); parsingFunction = ParsingFunction.ReaderClosed; }
internal void Close( bool closeStream ) { coreReaderImpl.Close( closeStream ); parsingFunction = ParsingFunction.ReaderClosed; }
// Resolves the current entity reference node public override void ResolveEntity() { if ( parsingFunction == ParsingFunction.ResolveEntityInternally ) { parsingFunction = ParsingFunction.Read; } coreReader.ResolveEntity(); }
// Iterates through the current attribute value's text and entity references chunks. public override bool ReadAttributeValue() { if ( parsingFunction == ParsingFunction.InReadBinaryContent ) { parsingFunction = ParsingFunction.Read; readBinaryHelper.Finish(); } if (!coreReader.ReadAttributeValue()) { return false; } parsingFunction = ParsingFunction.Read; return true; }
// Reads and validated next node from the input data public override bool Read() { switch ( parsingFunction ) { case ParsingFunction.Read: if ( coreReader.Read() ) { ProcessCoreReaderEvent(); return true; } else { validator.CompleteValidation(); return false; } case ParsingFunction.ParseDtdFromContext: parsingFunction = ParsingFunction.Read; ParseDtdFromParserContext(); goto case ParsingFunction.Read; case ParsingFunction.Error: case ParsingFunction.ReaderClosed: return false; case ParsingFunction.Init: parsingFunction = ParsingFunction.Read; // this changes the value returned by ReadState if ( coreReader.ReadState == ReadState.Interactive ) { ProcessCoreReaderEvent(); return true; } else { goto case ParsingFunction.Read; } case ParsingFunction.ResolveEntityInternally: parsingFunction = ParsingFunction.Read; ResolveEntityInternally(); goto case ParsingFunction.Read; case ParsingFunction.InReadBinaryContent: parsingFunction = ParsingFunction.Read; readBinaryHelper.Finish(); goto case ParsingFunction.Read; default: Debug.Assert( false ); return false; } }
// Moves to the next attribute of the current node public override bool MoveToNextAttribute() { if ( !coreReader.MoveToNextAttribute() ) { return false; } parsingFunction = ParsingFunction.Read; return true; }
public XmlTextReaderImpl(string url, XmlNameTable nt) : this(nt) { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (url.Length == 0) { throw new ArgumentException(SR.Xml_EmptyUrl, nameof(url)); } _namespaceManager = new XmlNamespaceManager(nt); _url = url; // It is important to have valid resolver here to resolve the Xml url file path. // it is safe as this resolver will not be used to resolve DTD url's _ps.baseUri = GetTempResolver().ResolveUri(null, url); _ps.baseUriStr = _ps.baseUri.ToString(); _reportedBaseUri = _ps.baseUriStr; _parsingFunction = ParsingFunction.OpenUrl; }
private void OnEof() { Debug.Assert(_ps.isEof); _curNode = _nodes[0]; _curNode.Clear(XmlNodeType.None); _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); _parsingFunction = ParsingFunction.Eof; _readState = ReadState.EndOfFile; _reportedEncoding = null; }
// Parses DOCTYPE declaration private bool ParseDoctypeDecl() { if (_dtdProcessing == DtdProcessing.Prohibit) { ThrowWithoutLineInfo(_v1Compat ? SR.Xml_DtdIsProhibited : SR.Xml_DtdIsProhibitedEx); } // parse 'DOCTYPE' while (_ps.charsUsed - _ps.charPos < 8) { if (ReadData() == 0) { Throw(SR.Xml_UnexpectedEOF, "DOCTYPE"); } } if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 7, "DOCTYPE")) { ThrowUnexpectedToken((!_rootElementParsed && _dtdInfo == null) ? "DOCTYPE" : "<!--"); } if (!_xmlCharType.IsWhiteSpace(_ps.chars[_ps.charPos + 7])) { ThrowExpectingWhitespace(_ps.charPos + 7); } if (_dtdInfo != null) { Throw(_ps.charPos - 2, SR.Xml_MultipleDTDsProvided); // position just before <!DOCTYPE } if (_rootElementParsed) { Throw(_ps.charPos - 2, SR.Xml_DtdAfterRootElement); } _ps.charPos += 8; EatWhitespaces(null); if (_dtdProcessing == DtdProcessing.Parse) { _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); ParseDtd(); _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.ResetAttributesRootLevel; return true; } // Skip DTD else { Debug.Assert(_dtdProcessing == DtdProcessing.Ignore); SkipDtd(); return false; } }
private void SetupEndEntityNodeInContent() { Debug.Assert(_lastEntity != null); _reportedEncoding = _ps.encoding; _reportedBaseUri = _ps.baseUriStr; _curNode = _nodes[_index]; Debug.Assert(_curNode.depth == _index); _curNode.SetNamedNode(XmlNodeType.EndEntity, _lastEntity.Name); _curNode.lineInfo.Set(_ps.lineNo, _ps.LinePos - 1); if (_index == 0 && _parsingFunction == ParsingFunction.ElementContent) { _parsingFunction = ParsingFunction.DocumentContent; } }
private void FinishReadContentAsBinary() { Debug.Assert(_parsingFunction == ParsingFunction.InReadContentAsBinary || _parsingFunction == ParsingFunction.InReadElementContentAsBinary); _readValueOffset = 0; if (_incReadState == IncrementalReadState.ReadContentAsBinary_OnPartialValue) { Debug.Assert((_index > 0) ? _nextParsingFunction == ParsingFunction.ElementContent : _nextParsingFunction == ParsingFunction.DocumentContent); SkipPartialTextValue(); } else { _parsingFunction = _nextParsingFunction; _nextParsingFunction = _nextNextParsingFunction; } if (_incReadState != IncrementalReadState.ReadContentAsBinary_End) { while (MoveToNextContentNode(true)) ; } }
private void FinishReadValueChunk() { Debug.Assert(_parsingFunction == ParsingFunction.InReadValueChunk); _readValueOffset = 0; if (_incReadState == IncrementalReadState.ReadValueChunk_OnPartialValue) { Debug.Assert((_index > 0) ? _nextParsingFunction == ParsingFunction.ElementContent : _nextParsingFunction == ParsingFunction.DocumentContent); SkipPartialTextValue(); } else { _parsingFunction = _nextParsingFunction; _nextParsingFunction = _nextNextParsingFunction; } }
private void SkipPartialTextValue() { Debug.Assert(_parsingFunction == ParsingFunction.PartialTextValue || _parsingFunction == ParsingFunction.InReadValueChunk || _parsingFunction == ParsingFunction.InReadContentAsBinary || _parsingFunction == ParsingFunction.InReadElementContentAsBinary); int startPos; int endPos; int orChars = 0; _parsingFunction = _nextParsingFunction; while (!ParseText(out startPos, out endPos, ref orChars)) ; }
// Parses a chunk of text starting at ps.charPos. // startPos .... start position of the text chunk that has been parsed (can differ from ps.charPos before the call) // endPos ...... end position of the text chunk that has been parsed (can differ from ps.charPos after the call) // ourOrChars .. all parsed character bigger or equal to 0x20 or-ed (|) into a single int. It can be used for whitespace detection // (the text has a non-whitespace character if outOrChars > 0x20). // Returns true when the whole value has been parsed. Return false when it needs to be called again to get a next chunk of value. private bool ParseText(out int startPos, out int endPos, ref int outOrChars) { char[] chars = _ps.chars; int pos = _ps.charPos; int rcount = 0; int rpos = -1; int orChars = outOrChars; char c; for (;;) { // parse text content unsafe { while (_xmlCharType.IsTextChar(c = chars[pos])) { orChars |= (int)c; pos++; } } switch (c) { case (char)0x9: pos++; continue; // eol case (char)0xA: pos++; OnNewLine(pos); continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { if (!_ps.eolNormalized && _parsingMode == ParsingMode.Full) { if (pos - _ps.charPos > 0) { if (rcount == 0) { rcount = 1; rpos = pos; } else { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); rpos = pos - rcount; rcount++; } } else { _ps.charPos++; } } pos += 2; } else if (pos + 1 < _ps.charsUsed || _ps.isEof) { if (!_ps.eolNormalized) { chars[pos] = (char)0xA; // EOL normalization of 0xD } pos++; } else { goto ReadData; } OnNewLine(pos); continue; // some tag case '<': goto ReturnPartialValue; // entity reference case '&': // try to parse char entity inline int charRefEndPos, charCount; EntityType entityType; if ((charRefEndPos = ParseCharRefInline(pos, out charCount, out entityType)) > 0) { if (rcount > 0) { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); } rpos = pos - rcount; rcount += (charRefEndPos - pos - charCount); pos = charRefEndPos; if (!_xmlCharType.IsWhiteSpace(chars[charRefEndPos - charCount]) || (_v1Compat && entityType == EntityType.CharacterDec)) { orChars |= 0xFF; } } else { if (pos > _ps.charPos) { goto ReturnPartialValue; } switch (HandleEntityReference(false, EntityExpandType.All, out pos)) { case EntityType.Unexpanded: // make sure we will report EntityReference after the text node _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.EntityReference; // end the value (returns nothing) goto NoValue; case EntityType.CharacterDec: if (!_v1Compat) { goto case EntityType.CharacterHex; } orChars |= 0xFF; break; case EntityType.CharacterHex: case EntityType.CharacterNamed: if (!_xmlCharType.IsWhiteSpace(_ps.chars[pos - 1])) { orChars |= 0xFF; } break; default: pos = _ps.charPos; break; } chars = _ps.chars; } continue; case ']': if (_ps.charsUsed - pos < 3 && !_ps.isEof) { goto ReadData; } if (chars[pos + 1] == ']' && chars[pos + 2] == '>') { Throw(pos, SR.Xml_CDATAEndInText); } orChars |= ']'; pos++; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReadData; } // surrogate chars else { char ch = chars[pos]; if (XmlCharType.IsHighSurrogate(ch)) { if (pos + 1 == _ps.charsUsed) { goto ReadData; } pos++; if (XmlCharType.IsLowSurrogate(chars[pos])) { pos++; orChars |= ch; continue; } } int offset = pos - _ps.charPos; if (ZeroEndingStream(pos)) { chars = _ps.chars; pos = _ps.charPos + offset; goto ReturnPartialValue; } else { ThrowInvalidChar(_ps.chars, _ps.charsUsed, _ps.charPos + offset); } break; } } ReadData: if (pos > _ps.charPos) { goto ReturnPartialValue; } // read new characters into the buffer if (ReadData() == 0) { if (_ps.charsUsed - _ps.charPos > 0) { if (_ps.chars[_ps.charPos] != (char)0xD && _ps.chars[_ps.charPos] != ']') { Throw(SR.Xml_UnexpectedEOF1); } Debug.Assert(_ps.isEof); } else { if (!InEntity) { // end the value (returns nothing) goto NoValue; } if (HandleEntityEnd(true)) { // report EndEntity after the text node _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.ReportEndEntity; // end the value (returns nothing) goto NoValue; } } } pos = _ps.charPos; chars = _ps.chars; continue; } NoValue: startPos = endPos = pos; return true; ReturnPartialValue: if (_parsingMode == ParsingMode.Full && rcount > 0) { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); } startPos = _ps.charPos; endPos = pos - rcount; _ps.charPos = pos; outOrChars = orChars; return c == '<'; }
private static Option <TValue> To <TValue>(string s, ParsingFunction <TValue> parsingFunction, Error error = null) { return(parsingFunction(s, out var result) ? result.Some() : Optional.None <TValue>(error ?? MissingReasons.CouldNotBeParsedAs <TValue> .Value)); }
private void InitIncrementalRead(IncrementalReadDecoder decoder) { ResetAttributes(); decoder.Reset(); _incReadDecoder = decoder; _incReadState = IncrementalReadState.Text; _incReadDepth = 1; _incReadLeftStartPos = _ps.charPos; _incReadLeftEndPos = _ps.charPos; _incReadLineInfo.Set(_ps.LineNo, _ps.LinePos); _parsingFunction = ParsingFunction.InIncrementalRead; }
public SerializerDataNode(SerializingFunction serializeFunction, ParsingFunction parsingFunction, WorldParsingFunction worldObjectParsingFunction) { serialize = serializeFunction; parse = parsingFunction; worldObj = worldObjectParsingFunction; }
// Moves to an attribute at the specified index (position) public override void MoveToAttribute( int i ) { coreReader.MoveToAttribute( i ); parsingFunction = ParsingFunction.Read; }
private bool ParseFragmentAttribute() { Debug.Assert(_fragmentType == XmlNodeType.Attribute); // if first call then parse the whole attribute value if (_curNode.type == XmlNodeType.None) { _curNode.type = XmlNodeType.Attribute; _curAttrIndex = 0; ParseAttributeValueSlow(_ps.charPos, ' ', _curNode); // The quote char is intentionally empty (space) because we need to parse ' and " into the attribute value } else { _parsingFunction = ParsingFunction.InReadAttributeValue; } // return attribute value chunk if (ReadAttributeValue()) { Debug.Assert(_parsingFunction == ParsingFunction.InReadAttributeValue); _parsingFunction = ParsingFunction.FragmentAttribute; return true; } else { OnEof(); return false; } }
// If on attribute, moves to the element that contains the attribute node public override bool MoveToElement() { if ( !coreReader.MoveToElement() ) { return false; } parsingFunction = ParsingFunction.Read; return true; }
private void SetupReadContentAsBinaryState(ParsingFunction inReadBinaryFunction) { if (_parsingFunction == ParsingFunction.PartialTextValue) { _incReadState = IncrementalReadState.ReadContentAsBinary_OnPartialValue; } else { _incReadState = IncrementalReadState.ReadContentAsBinary_OnCachedValue; _nextNextParsingFunction = _nextParsingFunction; _nextParsingFunction = _parsingFunction; } _readValueOffset = 0; _parsingFunction = inReadBinaryFunction; }
// Closes the input stream ot TextReader, changes the ReadState to Closed and sets all properties to zero/string.Empty public override void Close() { coreReader.Close(); parsingFunction = ParsingFunction.ReaderClosed; }
private int ReadContentAsBinary(byte[] buffer, int index, int count) { Debug.Assert(_incReadDecoder != null); if (_incReadState == IncrementalReadState.ReadContentAsBinary_End) { return 0; } _incReadDecoder.SetNextOutputBuffer(buffer, index, count); for (; ;) { // read what is already cached in curNode int charsRead = 0; try { charsRead = _curNode.CopyToBinary(_incReadDecoder, _readValueOffset); } // add line info to the exception catch (XmlException e) { _curNode.AdjustLineInfo(_readValueOffset, _ps.eolNormalized, ref _incReadLineInfo); ReThrow(e, _incReadLineInfo.lineNo, _incReadLineInfo.linePos); } _readValueOffset += charsRead; if (_incReadDecoder.IsFull) { return _incReadDecoder.DecodedCount; } // if on partial value, read the rest of it if (_incReadState == IncrementalReadState.ReadContentAsBinary_OnPartialValue) { _curNode.SetValue(string.Empty); // read next chunk of text bool endOfValue = false; int startPos = 0; int endPos = 0; while (!_incReadDecoder.IsFull && !endOfValue) { int orChars = 0; // store current line info and parse more text _incReadLineInfo.Set(_ps.LineNo, _ps.LinePos); endOfValue = ParseText(out startPos, out endPos, ref orChars); try { charsRead = _incReadDecoder.Decode(_ps.chars, startPos, endPos - startPos); } // add line info to the exception catch (XmlException e) { ReThrow(e, _incReadLineInfo.lineNo, _incReadLineInfo.linePos); } startPos += charsRead; } _incReadState = endOfValue ? IncrementalReadState.ReadContentAsBinary_OnCachedValue : IncrementalReadState.ReadContentAsBinary_OnPartialValue; _readValueOffset = 0; if (_incReadDecoder.IsFull) { _curNode.SetValue(_ps.chars, startPos, endPos - startPos); // adjust line info for the chunk that has been already decoded AdjustLineInfo(_ps.chars, startPos - charsRead, startPos, _ps.eolNormalized, ref _incReadLineInfo); _curNode.SetLineInfo(_incReadLineInfo.lineNo, _incReadLineInfo.linePos); return _incReadDecoder.DecodedCount; } } // reset to normal state so we can call Read() to move forward ParsingFunction tmp = _parsingFunction; _parsingFunction = _nextParsingFunction; _nextParsingFunction = _nextNextParsingFunction; // move to next textual node in the element content; throw on sub elements if (!MoveToNextContentNode(true)) { SetupReadContentAsBinaryState(tmp); _incReadState = IncrementalReadState.ReadContentAsBinary_End; return _incReadDecoder.DecodedCount; } SetupReadContentAsBinaryState(tmp); _incReadLineInfo.Set(_curNode.LineNo, _curNode.LinePos); } }
public override int ReadElementContentAsBinHex( byte[] buffer, int index, int count ) { if ( ReadState != ReadState.Interactive ) { return 0; } // init ReadChunkHelper when called first time if ( parsingFunction != ParsingFunction.InReadBinaryContent ) { readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset( readBinaryHelper, outerReader ); } // set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper parsingFunction = ParsingFunction.Read; // call to the helper int readCount = readBinaryHelper.ReadElementContentAsBinHex( buffer, index, count ); // setup parsingFunction parsingFunction = ParsingFunction.InReadBinaryContent; return readCount; }
private int ReadElementContentAsBinary(byte[] buffer, int index, int count) { if (count == 0) { return 0; } int decoded = ReadContentAsBinary(buffer, index, count); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_curNode.type != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _curNode.type.ToString(), this as IXmlLineInfo); } // reset state _parsingFunction = _nextParsingFunction; _nextParsingFunction = _nextNextParsingFunction; Debug.Assert(_parsingFunction != ParsingFunction.InReadElementContentAsBinary); // move off the EndElement _outerReader.Read(); return 0; }
// // Internal methods for validators, DOM, XPathDocument etc. // private void ProcessCoreReaderEvent() { switch ( coreReader.NodeType ) { case XmlNodeType.Whitespace: if ( coreReader.Depth > 0 || coreReaderImpl.FragmentType != XmlNodeType.Document ) { if ( validator.PreserveWhitespace ) { coreReaderImpl.ChangeCurrentNodeType( XmlNodeType.SignificantWhitespace ); } } goto default; case XmlNodeType.DocumentType: ValidateDtd(); break; case XmlNodeType.EntityReference: parsingFunction = ParsingFunction.ResolveEntityInternally; goto default; default: coreReaderImpl.InternalSchemaType = null; coreReaderImpl.InternalTypedValue = null; validator.Validate(); break; } }
// Reads the attributes private void ParseAttributes() { int pos = _ps.charPos; char[] chars = _ps.chars; NodeData attr = null; Debug.Assert(_attrCount == 0); for (;;) { // eat whitespaces int lineNoDelta = 0; char tmpch0; unsafe { while (_xmlCharType.IsWhiteSpace(tmpch0 = chars[pos])) { if (tmpch0 == (char)0xA) { OnNewLine(pos + 1); lineNoDelta++; } else if (tmpch0 == (char)0xD) { if (chars[pos + 1] == (char)0xA) { OnNewLine(pos + 2); lineNoDelta++; pos++; } else if (pos + 1 != _ps.charsUsed) { OnNewLine(pos + 1); lineNoDelta++; } else { _ps.charPos = pos; goto ReadData; } } pos++; } } char tmpch1; int startNameCharSize = 0; unsafe { if (_xmlCharType.IsStartNCNameSingleChar(tmpch1 = chars[pos])) { startNameCharSize = 1; } #if XML10_FIFTH_EDITION else if (pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar(chars[pos + 1], tmpch1)) { startNameCharSize = 2; } #endif } if (startNameCharSize == 0) { // element end if (tmpch1 == '>') { Debug.Assert(_curNode.type == XmlNodeType.Element); _ps.charPos = pos + 1; _parsingFunction = ParsingFunction.MoveToElementContent; goto End; } // empty element end else if (tmpch1 == '/') { Debug.Assert(_curNode.type == XmlNodeType.Element); if (pos + 1 == _ps.charsUsed) { goto ReadData; } if (chars[pos + 1] == '>') { _ps.charPos = pos + 2; _curNode.IsEmptyElement = true; _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.PopEmptyElementContext; goto End; } else { ThrowUnexpectedToken(pos + 1, ">"); } } else if (pos == _ps.charsUsed) { goto ReadData; } else if (tmpch1 != ':' || _supportNamespaces) { Throw(pos, SR.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(chars, _ps.charsUsed, pos)); } } if (pos == _ps.charPos) { ThrowExpectingWhitespace(pos); } _ps.charPos = pos; // save attribute name line position int attrNameLinePos = _ps.LinePos; #if DEBUG int attrNameLineNo = _ps.LineNo; #endif // parse attribute name int colonPos = -1; // PERF: we intentionally don't call ParseQName here to parse the element name unless a special // case occurs (like end of buffer, invalid name char) pos += startNameCharSize; // start name char has already been checked // parse attribute name ContinueParseName: char tmpch2; unsafe { for (;;) { if (_xmlCharType.IsNCNameSingleChar(tmpch2 = chars[pos])) { pos++; } #if XML10_FIFTH_EDITION else if (pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar(chars[pos + 1], tmpch2)) { pos += 2; } #endif else { break; } } } // colon -> save prefix end position and check next char if it's name start char if (tmpch2 == ':') { if (colonPos != -1) { if (_supportNamespaces) { Throw(pos, SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(':', '\0')); } else { pos++; goto ContinueParseName; } } else { colonPos = pos; pos++; unsafe { if (_xmlCharType.IsStartNCNameSingleChar(chars[pos])) { pos++; goto ContinueParseName; } #if XML10_FIFTH_EDITION else if ( pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar( chars[pos + 1], chars[pos] ) ) { pos += 2; goto ContinueParseName; } #endif } // else fallback to full name parsing routine pos = ParseQName(out colonPos); chars = _ps.chars; } } else if (pos + 1 >= _ps.charsUsed) { pos = ParseQName(out colonPos); chars = _ps.chars; } attr = AddAttribute(pos, colonPos); attr.SetLineInfo(_ps.LineNo, attrNameLinePos); #if DEBUG Debug.Assert(attrNameLineNo == _ps.LineNo); #endif // parse equals and quote char; if (chars[pos] != '=') { _ps.charPos = pos; EatWhitespaces(null); pos = _ps.charPos; if (chars[pos] != '=') { ThrowUnexpectedToken("="); } } pos++; char quoteChar = chars[pos]; if (quoteChar != '"' && quoteChar != '\'') { _ps.charPos = pos; EatWhitespaces(null); pos = _ps.charPos; quoteChar = chars[pos]; if (quoteChar != '"' && quoteChar != '\'') { ThrowUnexpectedToken("\"", "'"); } } pos++; _ps.charPos = pos; attr.quoteChar = quoteChar; attr.SetLineInfo2(_ps.LineNo, _ps.LinePos); // parse attribute value char tmpch3; unsafe { while (_xmlCharType.IsAttributeValueChar(tmpch3 = chars[pos])) { pos++; } } if (tmpch3 == quoteChar) { #if DEBUG if (_normalize) { string val = new string(chars, _ps.charPos, pos - _ps.charPos); Debug.Assert(val == XmlComplianceUtil.CDataNormalize(val), "The attribute value is not CDATA normalized!"); } #endif attr.SetValue(chars, _ps.charPos, pos - _ps.charPos); pos++; _ps.charPos = pos; } else { ParseAttributeValueSlow(pos, quoteChar, attr); pos = _ps.charPos; chars = _ps.chars; } // handle special attributes: if (attr.prefix.Length == 0) { // default namespace declaration if (Ref.Equal(attr.localName, _xmlNs)) { OnDefaultNamespaceDecl(attr); } } else { // prefixed namespace declaration if (Ref.Equal(attr.prefix, _xmlNs)) { OnNamespaceDecl(attr); } // xml: attribute else if (Ref.Equal(attr.prefix, _xml)) { OnXmlReservedAttribute(attr); } } continue; ReadData: _ps.lineNo -= lineNoDelta; if (ReadData() != 0) { pos = _ps.charPos; chars = _ps.chars; } else { ThrowUnclosedElements(); } } End: if (_addDefaultAttributesAndNormalize) { AddDefaultAttributesAndNormalize(); } // lookup namespaces: element ElementNamespaceLookup(); // lookup namespaces: attributes if (_attrNeedNamespaceLookup) { AttributeNamespaceLookup(); _attrNeedNamespaceLookup = false; } // check duplicate attributes if (_attrDuplWalkCount >= MaxAttrDuplWalkCount) { AttributeDuplCheck(); } }
// parses the element end tag private void ParseEndElement() { // check if the end tag name equals start tag name NodeData startTagNode = _nodes[_index - 1]; int prefLen = startTagNode.prefix.Length; int locLen = startTagNode.localName.Length; while (_ps.charsUsed - _ps.charPos < prefLen + locLen + 1) { if (ReadData() == 0) { break; } } int nameLen; char[] chars = _ps.chars; if (startTagNode.prefix.Length == 0) { if (!XmlConvert.StrEqual(chars, _ps.charPos, locLen, startTagNode.localName)) { ThrowTagMismatch(startTagNode); } nameLen = locLen; } else { int colonPos = _ps.charPos + prefLen; if (!XmlConvert.StrEqual(chars, _ps.charPos, prefLen, startTagNode.prefix) || chars[colonPos] != ':' || !XmlConvert.StrEqual(chars, colonPos + 1, locLen, startTagNode.localName)) { ThrowTagMismatch(startTagNode); } nameLen = locLen + prefLen + 1; } LineInfo endTagLineInfo = new LineInfo(_ps.lineNo, _ps.LinePos); int pos; for (;;) { pos = _ps.charPos + nameLen; chars = _ps.chars; if (pos == _ps.charsUsed) { goto ReadData; } unsafe { if (_xmlCharType.IsNCNameSingleChar(chars[pos]) || (chars[pos] == ':') #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(chars[pos]) #endif ) { ThrowTagMismatch(startTagNode); } } // eat whitespaces if (chars[pos] != '>') { char tmpCh; while (_xmlCharType.IsWhiteSpace(tmpCh = chars[pos])) { pos++; switch (tmpCh) { case (char)0xA: OnNewLine(pos); continue; case (char)0xD: if (chars[pos] == (char)0xA) { pos++; } else if (pos == _ps.charsUsed && !_ps.isEof) { break; } OnNewLine(pos); continue; } } } if (chars[pos] == '>') { break; } else if (pos == _ps.charsUsed) { goto ReadData; } else { ThrowUnexpectedToken(pos, ">"); } Debug.Assert(false, "We should never get to this point."); ReadData: if (ReadData() == 0) { ThrowUnclosedElements(); } } Debug.Assert(_index > 0); _index--; _curNode = _nodes[_index]; // set the element data Debug.Assert(_curNode == startTagNode); startTagNode.lineInfo = endTagLineInfo; startTagNode.type = XmlNodeType.EndElement; _ps.charPos = pos + 1; // set next parsing function _nextParsingFunction = (_index > 0) ? _parsingFunction : ParsingFunction.DocumentContent; _parsingFunction = ParsingFunction.PopElementContext; }
internal XmlValidatingReaderImpl( Stream xmlFragment, XmlNodeType fragType, XmlParserContext context ) : this( new XmlTextReader( xmlFragment, fragType, context ) ) { if ( coreReader.BaseURI.Length > 0 ) { validator.BaseUri = GetResolver().ResolveUri( null, coreReader.BaseURI ); } if ( context != null ) { parsingFunction = ParsingFunction.ParseDtdFromContext; parserContext = context; } }
// Moves to an attribute at the specified index (position) public override void MoveToAttribute(int i) { coreReader.MoveToAttribute(i); parsingFunction = ParsingFunction.Read; }
// Moves to an attribute with the specified Name public override bool MoveToAttribute( string name ) { if ( !coreReader.MoveToAttribute( name ) ) { return false; } parsingFunction = ParsingFunction.Read; return true; }
// Moves to an attribute with the specified LocalName and NamespceURI public override bool MoveToAttribute( string localName, string namespaceURI ) { if ( !coreReader.MoveToAttribute( localName, namespaceURI ) ) { return false; } parsingFunction = ParsingFunction.Read; return true; }
private int IncrementalRead() { int charsDecoded = 0; OuterContinue: int charsLeft = _incReadLeftEndPos - _incReadLeftStartPos; if (charsLeft > 0) { int count; try { count = _incReadDecoder.Decode(_ps.chars, _incReadLeftStartPos, charsLeft); } catch (XmlException e) { ReThrow(e, (int)_incReadLineInfo.lineNo, (int)_incReadLineInfo.linePos); return 0; } if (count < charsLeft) { _incReadLeftStartPos += count; _incReadLineInfo.linePos += count; // we have never more then 1 line cached return count; } else { _incReadLeftStartPos = 0; _incReadLeftEndPos = 0; _incReadLineInfo.linePos += count; if (_incReadDecoder.IsFull) { return count; } } } int startPos = 0; int pos = 0; for (;;) { switch (_incReadState) { case IncrementalReadState.Text: case IncrementalReadState.Attributes: case IncrementalReadState.AttributeValue: break; case IncrementalReadState.PI: if (ParsePIValue(out startPos, out pos)) { Debug.Assert(XmlConvert.StrEqual(_ps.chars, _ps.charPos - 2, 2, "?>")); _ps.charPos -= 2; _incReadState = IncrementalReadState.Text; } goto Append; case IncrementalReadState.Comment: if (ParseCDataOrComment(XmlNodeType.Comment, out startPos, out pos)) { Debug.Assert(XmlConvert.StrEqual(_ps.chars, _ps.charPos - 3, 3, "-->")); _ps.charPos -= 3; _incReadState = IncrementalReadState.Text; } goto Append; case IncrementalReadState.CDATA: if (ParseCDataOrComment(XmlNodeType.CDATA, out startPos, out pos)) { Debug.Assert(XmlConvert.StrEqual(_ps.chars, _ps.charPos - 3, 3, "]]>")); _ps.charPos -= 3; _incReadState = IncrementalReadState.Text; } goto Append; case IncrementalReadState.EndElement: _parsingFunction = ParsingFunction.PopElementContext; _nextParsingFunction = (_index > 0 || _fragmentType != XmlNodeType.Document) ? ParsingFunction.ElementContent : ParsingFunction.DocumentContent; _outerReader.Read(); _incReadState = IncrementalReadState.End; goto case IncrementalReadState.End; case IncrementalReadState.End: return charsDecoded; case IncrementalReadState.ReadData: if (ReadData() == 0) { ThrowUnclosedElements(); } _incReadState = IncrementalReadState.Text; startPos = _ps.charPos; pos = startPos; break; default: Debug.Assert(false); break; } Debug.Assert(_incReadState == IncrementalReadState.Text || _incReadState == IncrementalReadState.Attributes || _incReadState == IncrementalReadState.AttributeValue); char[] chars = _ps.chars; startPos = _ps.charPos; pos = startPos; for (;;) { _incReadLineInfo.Set(_ps.LineNo, _ps.LinePos); char c; unsafe { if (_incReadState == IncrementalReadState.Attributes) { while (_xmlCharType.IsAttributeValueChar(c = chars[pos]) && c != '/') { pos++; } } else { while (_xmlCharType.IsAttributeValueChar(c = chars[pos])) { pos++; } } } if (chars[pos] == '&' || chars[pos] == (char)0x9) { pos++; continue; } if (pos - startPos > 0) { goto AppendAndUpdateCharPos; } switch (chars[pos]) { // eol case (char)0xA: pos++; OnNewLine(pos); continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { pos += 2; } else if (pos + 1 < _ps.charsUsed) { pos++; } else { goto ReadData; } OnNewLine(pos); continue; // some tag case '<': if (_incReadState != IncrementalReadState.Text) { pos++; continue; } if (_ps.charsUsed - pos < 2) { goto ReadData; } switch (chars[pos + 1]) { // pi case '?': pos += 2; _incReadState = IncrementalReadState.PI; goto AppendAndUpdateCharPos; // comment case '!': if (_ps.charsUsed - pos < 4) { goto ReadData; } if (chars[pos + 2] == '-' && chars[pos + 3] == '-') { pos += 4; _incReadState = IncrementalReadState.Comment; goto AppendAndUpdateCharPos; } if (_ps.charsUsed - pos < 9) { goto ReadData; } if (XmlConvert.StrEqual(chars, pos + 2, 7, "[CDATA[")) { pos += 9; _incReadState = IncrementalReadState.CDATA; goto AppendAndUpdateCharPos; } else { ;//Throw( ); } break; // end tag case '/': { Debug.Assert(_ps.charPos - pos == 0); Debug.Assert(_ps.charPos - startPos == 0); int colonPos; // ParseQName can flush the buffer, so we need to update the startPos, pos and chars after calling it int endPos = ParseQName(true, 2, out colonPos); if (XmlConvert.StrEqual(chars, _ps.charPos + 2, endPos - _ps.charPos - 2, _curNode.GetNameWPrefix(_nameTable)) && (_ps.chars[endPos] == '>' || _xmlCharType.IsWhiteSpace(_ps.chars[endPos]))) { if (--_incReadDepth > 0) { pos = endPos + 1; continue; } _ps.charPos = endPos; if (_xmlCharType.IsWhiteSpace(_ps.chars[endPos])) { EatWhitespaces(null); } if (_ps.chars[_ps.charPos] != '>') { ThrowUnexpectedToken(">"); } _ps.charPos++; _incReadState = IncrementalReadState.EndElement; goto OuterContinue; } else { pos = endPos; startPos = _ps.charPos; chars = _ps.chars; continue; } } // start tag default: { Debug.Assert(_ps.charPos - pos == 0); Debug.Assert(_ps.charPos - startPos == 0); int colonPos; // ParseQName can flush the buffer, so we need to update the startPos, pos and chars after calling it int endPos = ParseQName(true, 1, out colonPos); if (XmlConvert.StrEqual(_ps.chars, _ps.charPos + 1, endPos - _ps.charPos - 1, _curNode.localName) && (_ps.chars[endPos] == '>' || _ps.chars[endPos] == '/' || _xmlCharType.IsWhiteSpace(_ps.chars[endPos]))) { _incReadDepth++; _incReadState = IncrementalReadState.Attributes; pos = endPos; goto AppendAndUpdateCharPos; } pos = endPos; startPos = _ps.charPos; chars = _ps.chars; continue; } } break; // end of start tag case '/': if (_incReadState == IncrementalReadState.Attributes) { if (_ps.charsUsed - pos < 2) { goto ReadData; } if (chars[pos + 1] == '>') { _incReadState = IncrementalReadState.Text; _incReadDepth--; } } pos++; continue; // end of start tag case '>': if (_incReadState == IncrementalReadState.Attributes) { _incReadState = IncrementalReadState.Text; } pos++; continue; case '"': case '\'': switch (_incReadState) { case IncrementalReadState.AttributeValue: if (chars[pos] == _curNode.quoteChar) { _incReadState = IncrementalReadState.Attributes; } break; case IncrementalReadState.Attributes: _curNode.quoteChar = chars[pos]; _incReadState = IncrementalReadState.AttributeValue; break; } pos++; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReadData; } // surrogate chars or invalid chars are ignored else { pos++; continue; } } } ReadData: _incReadState = IncrementalReadState.ReadData; AppendAndUpdateCharPos: _ps.charPos = pos; Append: // decode characters int charsParsed = pos - startPos; if (charsParsed > 0) { int count; try { count = _incReadDecoder.Decode(_ps.chars, startPos, charsParsed); } catch (XmlException e) { ReThrow(e, (int)_incReadLineInfo.lineNo, (int)_incReadLineInfo.linePos); return 0; } Debug.Assert(count == charsParsed || _incReadDecoder.IsFull, "Check if decoded consumed all characters unless it's full."); charsDecoded += count; if (_incReadDecoder.IsFull) { _incReadLeftStartPos = startPos + count; _incReadLeftEndPos = pos; _incReadLineInfo.linePos += count; // we have never more than 1 line cached return charsDecoded; } } } }
// Parses text or white space node. // Returns true if a node has been parsed and its data set to curNode. // Returns false when a white space has been parsed and ignored (according to current whitespace handling) or when parsing mode is not Full. // Also returns false if there is no text to be parsed. private bool ParseText() { int startPos; int endPos; int orChars = 0; // skip over the text if not in full parsing mode if (_parsingMode != ParsingMode.Full) { while (!ParseText(out startPos, out endPos, ref orChars)) ; goto IgnoredNode; } _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); Debug.Assert(_stringBuilder.Length == 0); // the whole value is in buffer if (ParseText(out startPos, out endPos, ref orChars)) { if (endPos - startPos == 0) { goto IgnoredNode; } XmlNodeType nodeType = GetTextNodeType(orChars); if (nodeType == XmlNodeType.None) { goto IgnoredNode; } Debug.Assert(endPos - startPos > 0); _curNode.SetValueNode(nodeType, _ps.chars, startPos, endPos - startPos); return true; } // only piece of the value was returned else { // V1 compatibility mode -> cache the whole value if (_v1Compat) { do { if (endPos - startPos > 0) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } } while (!ParseText(out startPos, out endPos, ref orChars)); if (endPos - startPos > 0) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } Debug.Assert(_stringBuilder.Length > 0); XmlNodeType nodeType = GetTextNodeType(orChars); if (nodeType == XmlNodeType.None) { _stringBuilder.Length = 0; goto IgnoredNode; } _curNode.SetValueNode(nodeType, _stringBuilder.ToString()); _stringBuilder.Length = 0; return true; } // V2 reader -> do not cache the whole value yet, read only up to 4kB to decide whether the value is a whitespace else { bool fullValue = false; // if it's a partial text value, not a whitespace -> return if (orChars > 0x20) { Debug.Assert(endPos - startPos > 0); _curNode.SetValueNode(XmlNodeType.Text, _ps.chars, startPos, endPos - startPos); _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.PartialTextValue; return true; } // partial whitespace -> read more data (up to 4kB) to decide if it is a whitespace or a text node if (endPos - startPos > 0) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } do { fullValue = ParseText(out startPos, out endPos, ref orChars); if (endPos - startPos > 0) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } } while (!fullValue && orChars <= 0x20 && _stringBuilder.Length < MinWhitespaceLookahedCount); // determine the value node type XmlNodeType nodeType = (_stringBuilder.Length < MinWhitespaceLookahedCount) ? GetTextNodeType(orChars) : XmlNodeType.Text; if (nodeType == XmlNodeType.None) { // ignored whitespace -> skip over the rest of the value unless we already read it all _stringBuilder.Length = 0; if (!fullValue) { while (!ParseText(out startPos, out endPos, ref orChars)) ; } goto IgnoredNode; } // set value to curNode _curNode.SetValueNode(nodeType, _stringBuilder.ToString()); _stringBuilder.Length = 0; // change parsing state if the full value was not parsed if (!fullValue) { _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.PartialTextValue; } return true; } } IgnoredNode: // ignored whitespace at the end of manually resolved entity if (_parsingFunction == ParsingFunction.ReportEndEntity) { SetupEndEntityNodeInContent(); _parsingFunction = _nextParsingFunction; return true; } else if (_parsingFunction == ParsingFunction.EntityReference) { _parsingFunction = _nextNextParsingFunction; ParseEntityReference(); return true; } return false; }