public virtual void AddNamespace(string prefix, string uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (prefix == null) { throw new ArgumentNullException("prefix"); } prefix = nameTable.Add(prefix); uri = nameTable.Add(uri); if ((Ref.Equal(xml, prefix) && !uri.Equals(XmlReservedNs.NsXml))) { throw new ArgumentException(Res.GetString(Res.Xml_XmlPrefix)); } if (Ref.Equal(xmlNs, prefix)) { throw new ArgumentException(Res.GetString(Res.Xml_XmlnsPrefix)); } int declIndex = LookupNamespaceDecl(prefix); int previousDeclIndex = -1; if (declIndex != -1) { if (nsdecls[declIndex].scopeId == scopeId) { // redefine if in the same scope nsdecls[declIndex].uri = uri; return; } else { // othewise link previousDeclIndex = declIndex; } } // set new namespace declaration if (lastDecl == nsdecls.Length - 1) { NamespaceDeclaration[] newNsdecls = new NamespaceDeclaration[nsdecls.Length * 2]; Array.Copy(nsdecls, 0, newNsdecls, 0, nsdecls.Length); nsdecls = newNsdecls; } nsdecls[++lastDecl].Set(prefix, uri, scopeId, previousDeclIndex); // add to hashTable if (useHashtable) { hashTable[prefix] = lastDecl; } // or create a new hashTable if the threashold has been reached else if (lastDecl >= MinDeclsCountForHashtable) { // add all to hash table Debug.Assert(hashTable == null); hashTable = new Dictionary <string, int>(lastDecl); for (int i = 0; i <= lastDecl; i++) { hashTable[nsdecls[i].prefix] = i; } useHashtable = true; } }
private XmlNode LoadEntityChildren() { XmlNode node = null; // We do not use creator functions on XmlDocument, b/c we do not want to let users extend the nodes that are children of entity nodes (also, if we do // this, XmlDataDocument will have a problem, b/c they do not know that those nodes should not be mapped). switch (reader.NodeType) { case XmlNodeType.EndElement: case XmlNodeType.EndEntity: break; case XmlNodeType.Element: { bool fEmptyElement = reader.IsEmptyElement; XmlElement element = new XmlElement(reader.Prefix, reader.LocalName, reader.NamespaceURI, this.doc); element.IsEmpty = fEmptyElement; while (reader.MoveToNextAttribute()) { XmlAttribute attr = (XmlAttribute)LoadEntityChildren(); element.Attributes.Append(attr); } // recursively load all children. if (!fEmptyElement) { LoadEntityChildren(element); } node = element; break; } case XmlNodeType.Attribute: if (reader.IsDefault) { XmlUnspecifiedAttribute attr = new XmlUnspecifiedAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI, this.doc); LoadEntityAttributeChildren(attr); attr.SetSpecified(false); node = attr; } else { XmlAttribute attr = new XmlAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI, this.doc); LoadEntityAttributeChildren(attr); node = attr; } break; case XmlNodeType.SignificantWhitespace: node = new XmlSignificantWhitespace(reader.Value, this.doc); break; case XmlNodeType.Whitespace: if (preserveWhitespace) { node = new XmlWhitespace(reader.Value, this.doc); } else { // if preserveWhitespace is false skip all subsequent WS nodes and position on the first non-WS node do { if (!reader.Read()) { return(null); } } while (reader.NodeType == XmlNodeType.Whitespace); node = LoadEntityChildren(); // Skip WS node if preserveWhitespace is false } break; case XmlNodeType.Text: node = new XmlText(reader.Value, this.doc); break; case XmlNodeType.CDATA: node = new XmlCDataSection(reader.Value, this.doc); break; case XmlNodeType.EntityReference: { XmlEntityReference eref = new XmlEntityReference(reader.Name, this.doc); if (reader.CanResolveEntity) { reader.ResolveEntity(); LoadEntityChildren(eref); //what if eref doesn't have children at all? should we just put a Empty String text here? if (eref.ChildNodes.Count == 0) { eref.AppendChild(new XmlText("")); } } node = eref; break; } case XmlNodeType.ProcessingInstruction: node = new XmlProcessingInstruction(reader.Name, reader.Value, this.doc); break; case XmlNodeType.Comment: node = new XmlComment(reader.Value, this.doc); break; default: throw new InvalidOperationException(string.Format(Res.GetString(Res.Xdom_Load_NodeType), reader.NodeType.ToString())); } return(node); }
private async Task WriteEndAttributeAsync_SepcialAtt() { try { string value; switch (specAttr) { case SpecialAttribute.DefaultXmlns: value = attrValueCache.StringValue; if (PushNamespaceExplicit(string.Empty, value)) // returns true if the namespace declaration should be written out { if (rawWriter != null) { if (rawWriter.SupportsNamespaceDeclarationInChunks) { await rawWriter.WriteStartNamespaceDeclarationAsync(string.Empty).ConfigureAwait(false); await attrValueCache.ReplayAsync(rawWriter).ConfigureAwait(false); await rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false); } else { await rawWriter.WriteNamespaceDeclarationAsync(string.Empty, value).ConfigureAwait(false); } } else { await writer.WriteStartAttributeAsync(string.Empty, "xmlns", XmlReservedNs.NsXmlNs).ConfigureAwait(false); await attrValueCache.ReplayAsync(writer).ConfigureAwait(false); await writer.WriteEndAttributeAsync().ConfigureAwait(false); } } curDeclPrefix = null; break; case SpecialAttribute.PrefixedXmlns: value = attrValueCache.StringValue; if (value.Length == 0) { throw new ArgumentException(Res.GetString(Res.Xml_PrefixForEmptyNs)); } if (value == XmlReservedNs.NsXmlNs || (value == XmlReservedNs.NsXml && curDeclPrefix != "xml")) { throw new ArgumentException(Res.GetString(Res.Xml_CanNotBindToReservedNamespace)); } if (PushNamespaceExplicit(curDeclPrefix, value)) // returns true if the namespace declaration should be written out { if (rawWriter != null) { if (rawWriter.SupportsNamespaceDeclarationInChunks) { await rawWriter.WriteStartNamespaceDeclarationAsync(curDeclPrefix).ConfigureAwait(false); await attrValueCache.ReplayAsync(rawWriter).ConfigureAwait(false); await rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false); } else { await rawWriter.WriteNamespaceDeclarationAsync(curDeclPrefix, value).ConfigureAwait(false); } } else { await writer.WriteStartAttributeAsync("xmlns", curDeclPrefix, XmlReservedNs.NsXmlNs).ConfigureAwait(false); await attrValueCache.ReplayAsync(writer).ConfigureAwait(false); await writer.WriteEndAttributeAsync().ConfigureAwait(false); } } curDeclPrefix = null; break; case SpecialAttribute.XmlSpace: attrValueCache.Trim(); value = attrValueCache.StringValue; if (value == "default") { elemScopeStack[elemTop].xmlSpace = XmlSpace.Default; } else if (value == "preserve") { elemScopeStack[elemTop].xmlSpace = XmlSpace.Preserve; } else { throw new ArgumentException(Res.GetString(Res.Xml_InvalidXmlSpace, value)); } await writer.WriteStartAttributeAsync("xml", "space", XmlReservedNs.NsXml).ConfigureAwait(false); await attrValueCache.ReplayAsync(writer).ConfigureAwait(false); await writer.WriteEndAttributeAsync().ConfigureAwait(false); break; case SpecialAttribute.XmlLang: value = attrValueCache.StringValue; elemScopeStack[elemTop].xmlLang = value; await writer.WriteStartAttributeAsync("xml", "lang", XmlReservedNs.NsXml).ConfigureAwait(false); await attrValueCache.ReplayAsync(writer).ConfigureAwait(false); await writer.WriteEndAttributeAsync().ConfigureAwait(false); break; } specAttr = SpecialAttribute.No; attrValueCache.Clear(); } catch { currentState = State.Error; throw; } }
internal XmlReader AddConformanceWrapper(XmlReader baseReader) { XmlReaderSettings baseReaderSettings = baseReader.Settings; bool checkChars = false; bool noWhitespace = false; bool noComments = false; bool noPIs = false; DtdProcessing dtdProc = (DtdProcessing)(-1); bool needWrap = false; if (baseReaderSettings == null) { #pragma warning disable 618 #if SILVERLIGHT // Starting from Windows phone 8.1 (TargetsAtLeast_Desktop_V4_5_1) we converge with the desktop behavior so we'll let the reader // not throw exception if has different conformance level than Auto. if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5_1) { if (this.conformanceLevel != ConformanceLevel.Auto && this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader)) { throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString())); } } else if (this.conformanceLevel != ConformanceLevel.Auto) { throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString())); } #else if (this.conformanceLevel != ConformanceLevel.Auto && this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader)) { throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString())); } #endif #if !SILVERLIGHT // get the V1 XmlTextReader ref XmlTextReader v1XmlTextReader = baseReader as XmlTextReader; if (v1XmlTextReader == null) { XmlValidatingReader vr = baseReader as XmlValidatingReader; if (vr != null) { v1XmlTextReader = (XmlTextReader)vr.Reader; } } #endif // assume the V1 readers already do all conformance checking; // wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true; if (this.ignoreWhitespace) { WhitespaceHandling wh = WhitespaceHandling.All; #if !SILVERLIGHT // special-case our V1 readers to see if whey already filter whitespaces if (v1XmlTextReader != null) { wh = v1XmlTextReader.WhitespaceHandling; } #endif if (wh == WhitespaceHandling.All) { noWhitespace = true; needWrap = true; } } if (this.ignoreComments) { noComments = true; needWrap = true; } if (this.ignorePIs) { noPIs = true; needWrap = true; } // DTD processing DtdProcessing baseDtdProcessing = DtdProcessing.Parse; #if !SILVERLIGHT if (v1XmlTextReader != null) { baseDtdProcessing = v1XmlTextReader.DtdProcessing; } #endif if ((this.dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) || (this.dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse)) { dtdProc = this.dtdProcessing; needWrap = true; } #pragma warning restore 618 } else { if (this.conformanceLevel != baseReaderSettings.ConformanceLevel && this.conformanceLevel != ConformanceLevel.Auto) { throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString())); } if (this.checkCharacters && !baseReaderSettings.CheckCharacters) { checkChars = true; needWrap = true; } if (this.ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace) { noWhitespace = true; needWrap = true; } if (this.ignoreComments && !baseReaderSettings.IgnoreComments) { noComments = true; needWrap = true; } if (this.ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions) { noPIs = true; needWrap = true; } if ((this.dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) || (this.dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse)) { dtdProc = this.dtdProcessing; needWrap = true; } } if (needWrap) { IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver; if (readerAsNSResolver != null) { return(new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc)); } else { return(new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc)); } } else { return(baseReader); } }
private Task WriteStartAttributeAsync_NoAdvanceState(string prefix, string localName, string namespaceName) { try { // lookup prefix / namespace if (prefix == null) { if (namespaceName != null) { // special case prefix=null/localname=xmlns if (!(localName == "xmlns" && namespaceName == XmlReservedNs.NsXmlNs)) { prefix = LookupPrefix(namespaceName); } } if (prefix == null) { prefix = string.Empty; } } if (namespaceName == null) { if (prefix != null && prefix.Length > 0) { namespaceName = LookupNamespace(prefix); } if (namespaceName == null) { namespaceName = string.Empty; } } if (prefix.Length == 0) { if (localName[0] == 'x' && localName == "xmlns") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs) { throw new ArgumentException(Res.GetString(Res.Xml_XmlnsPrefix)); } curDeclPrefix = String.Empty; SetSpecialAttribute(SpecialAttribute.DefaultXmlns); goto SkipPushAndWrite; } else if (namespaceName.Length > 0) { prefix = LookupPrefix(namespaceName); if (prefix == null || prefix.Length == 0) { prefix = GeneratePrefix(); } } } else { if (prefix[0] == 'x') { if (prefix == "xmlns") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs) { throw new ArgumentException(Res.GetString(Res.Xml_XmlnsPrefix)); } curDeclPrefix = localName; SetSpecialAttribute(SpecialAttribute.PrefixedXmlns); goto SkipPushAndWrite; } else if (prefix == "xml") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXml) { throw new ArgumentException(Res.GetString(Res.Xml_XmlPrefix)); } switch (localName) { case "space": SetSpecialAttribute(SpecialAttribute.XmlSpace); goto SkipPushAndWrite; case "lang": SetSpecialAttribute(SpecialAttribute.XmlLang); goto SkipPushAndWrite; } } } CheckNCName(prefix); if (namespaceName.Length == 0) { // attributes cannot have default namespace prefix = string.Empty; } else { string definedNs = LookupLocalNamespace(prefix); if (definedNs != null && definedNs != namespaceName) { prefix = GeneratePrefix(); } } } if (prefix.Length != 0) { PushNamespaceImplicit(prefix, namespaceName); } SkipPushAndWrite: // add attribute to the list and check for duplicates AddAttribute(prefix, localName, namespaceName); if (specAttr == SpecialAttribute.No) { // write attribute name return(TryReturnTask(writer.WriteStartAttributeAsync(prefix, localName, namespaceName))); } return(AsyncHelper.DoneTask); } catch { currentState = State.Error; throw; } }
public override async Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { try { if (name == null || name.Length == 0) { throw new ArgumentException(Res.GetString(Res.Xml_EmptyName)); } XmlConvert.VerifyQName(name, ExceptionType.XmlException); if (conformanceLevel == ConformanceLevel.Fragment) { throw new InvalidOperationException(Res.GetString(Res.Xml_DtdNotAllowedInFragment)); } await AdvanceStateAsync(Token.Dtd).ConfigureAwait(false); if (dtdWritten) { currentState = State.Error; throw new InvalidOperationException(Res.GetString(Res.Xml_DtdAlreadyWritten)); } if (conformanceLevel == ConformanceLevel.Auto) { conformanceLevel = ConformanceLevel.Document; stateTable = StateTableDocument; } int i; // check characters if (checkCharacters) { if (pubid != null) { if ((i = xmlCharType.IsPublicId(pubid)) >= 0) { throw new ArgumentException(Res.GetString(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(pubid, i)), "pubid"); } } if (sysid != null) { if ((i = xmlCharType.IsOnlyCharData(sysid)) >= 0) { throw new ArgumentException(Res.GetString(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(sysid, i)), "sysid"); } } if (subset != null) { if ((i = xmlCharType.IsOnlyCharData(subset)) >= 0) { throw new ArgumentException(Res.GetString(Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(subset, i)), "subset"); } } } // write doctype await writer.WriteDocTypeAsync(name, pubid, sysid, subset).ConfigureAwait(false); dtdWritten = true; } catch { currentState = State.Error; throw; } }
// Advance the state machine private Task AdvanceStateAsync(Token token) { if ((int)currentState >= (int)State.Closed) { if (currentState == State.Closed || currentState == State.Error) { throw new InvalidOperationException(Res.GetString(Res.Xml_ClosedOrError)); } else { throw new InvalidOperationException(Res.GetString(Res.Xml_WrongToken, tokenName[(int)token], GetStateName(currentState))); } } Advance: State newState = stateTable[((int)token << 4) + (int)currentState]; // [ (int)token * 16 + (int)currentState ]; Task task; if ((int)newState >= (int)State.Error) { switch (newState) { case State.Error: ThrowInvalidStateTransition(token, currentState); break; case State.StartContent: return(AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Content)); case State.StartContentEle: return(AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Element)); case State.StartContentB64: return(AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.B64Content)); case State.StartDoc: return(AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Document)); case State.StartDocEle: return(AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Element)); case State.EndAttrSEle: task = SequenceRun(WriteEndAttributeAsync(), StartElementContentAsync); return(AdvanceStateAsync_ReturnWhenFinish(task, State.Element)); case State.EndAttrEEle: task = SequenceRun(WriteEndAttributeAsync(), StartElementContentAsync); return(AdvanceStateAsync_ReturnWhenFinish(task, State.Content)); case State.EndAttrSCont: task = SequenceRun(WriteEndAttributeAsync(), StartElementContentAsync); return(AdvanceStateAsync_ReturnWhenFinish(task, State.Content)); case State.EndAttrSAttr: return(AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.Attribute)); case State.PostB64Cont: if (rawWriter != null) { return(AdvanceStateAsync_ContinueWhenFinish(rawWriter.WriteEndBase64Async(), State.Content, token)); } currentState = State.Content; goto Advance; case State.PostB64Attr: if (rawWriter != null) { return(AdvanceStateAsync_ContinueWhenFinish(rawWriter.WriteEndBase64Async(), State.Attribute, token)); } currentState = State.Attribute; goto Advance; case State.PostB64RootAttr: if (rawWriter != null) { return(AdvanceStateAsync_ContinueWhenFinish(rawWriter.WriteEndBase64Async(), State.RootLevelAttr, token)); } currentState = State.RootLevelAttr; goto Advance; case State.StartFragEle: StartFragment(); newState = State.Element; break; case State.StartFragCont: StartFragment(); newState = State.Content; break; case State.StartFragB64: StartFragment(); newState = State.B64Content; break; case State.StartRootLevelAttr: return(AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.RootLevelAttr)); default: Debug.Assert(false, "We should not get to this point."); break; } } currentState = newState; return(AsyncHelper.DoneTask); }
public bool Validate(XmlNode nodeToValidate) { XmlSchemaObject partialValidationType = null; XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes; Debug.Assert(nodeToValidate.SchemaInfo != null); startNode = nodeToValidate; switch (nodeToValidate.NodeType) { case XmlNodeType.Document: validationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints; break; case XmlNodeType.DocumentFragment: break; case XmlNodeType.Element: //Validate children of this element IXmlSchemaInfo schemaInfo = nodeToValidate.SchemaInfo; XmlSchemaElement schemaElement = schemaInfo.SchemaElement; if (schemaElement != null) { if (!schemaElement.RefName.IsEmpty) //If it is element ref, { partialValidationType = schemas.GlobalElements[schemaElement.QualifiedName]; //Get Global element with correct Nillable, Default etc } else //local element { partialValidationType = schemaElement; } //Verify that if there was xsi:type, the schemaElement returned has the correct type set Debug.Assert(schemaElement.ElementSchemaType == schemaInfo.SchemaType); } else //Can be an element that matched xs:any and had xsi:type { partialValidationType = schemaInfo.SchemaType; if (partialValidationType == null) //Validated against xs:any with pc= lax or skip or undeclared / not validated element { if (nodeToValidate.ParentNode.NodeType == XmlNodeType.Document) { //If this is the documentElement and it has not been validated at all nodeToValidate = nodeToValidate.ParentNode; } else { partialValidationType = FindSchemaInfo(nodeToValidate as XmlElement); if (partialValidationType == null) { throw new XmlSchemaValidationException(Res.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate); } } } } break; case XmlNodeType.Attribute: if (nodeToValidate.XPNodeType == XPathNodeType.Namespace) { goto default; } partialValidationType = nodeToValidate.SchemaInfo.SchemaAttribute; if (partialValidationType == null) //Validated against xs:anyAttribute with pc = lax or skip / undeclared attribute { partialValidationType = FindSchemaInfo(nodeToValidate as XmlAttribute); if (partialValidationType == null) { throw new XmlSchemaValidationException(Res.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate); } } break; default: throw new InvalidOperationException(Res.GetString(Res.XmlDocument_ValidateInvalidNodeType, null)); } isValid = true; CreateValidator(partialValidationType, validationFlags); if (psviAugmentation) { if (schemaInfo == null) //Might have created it during FindSchemaInfo { schemaInfo = new XmlSchemaInfo(); } attributeSchemaInfo = new XmlSchemaInfo(); } ValidateNode(nodeToValidate); validator.EndValidation(); return(isValid); }
private void ValidateNode(XmlNode node) { currentNode = node; switch (currentNode.NodeType) { case XmlNodeType.Document: XmlElement docElem = ((XmlDocument)node).DocumentElement; if (docElem == null) { throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidXmlDocument, Res.GetString(Res.Xdom_NoRootEle))); } ValidateNode(docElem); break; case XmlNodeType.DocumentFragment: case XmlNodeType.EntityReference: for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling) { ValidateNode(child); } break; case XmlNodeType.Element: ValidateElement(); break; case XmlNodeType.Attribute: //Top-level attribute XmlAttribute attr = currentNode as XmlAttribute; validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, nodeValueGetter, attributeSchemaInfo); if (psviAugmentation) { attr.XmlName = document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, attributeSchemaInfo); } break; case XmlNodeType.Text: if (validator.CurrentContentType == XmlSchemaContentType.ElementOnly && XmlCharType.Instance.IsOnlyWhitespace(currentNode.Value)) //The text node could contain only whitespaces { validator.ValidateWhitespace(nodeValueGetter); } else { validator.ValidateText(nodeValueGetter); } break; case XmlNodeType.CDATA: validator.ValidateText(nodeValueGetter); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: validator.ValidateWhitespace(nodeValueGetter); break; case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: break; default: throw new InvalidOperationException(Res.GetString(Res.Xml_UnexpectedNodeType, new string[] { currentNode.NodeType.ToString() })); } }
///<include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.ToTimeSpan"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static TimeSpan ToTimeSpan(string s) { bool negate = false; int years = 0; int months = 0; int days = 0; int hours = 0; int minutes = 0; int seconds = 0; double milliseconds = 0; s = s.Trim(); int length = s.Length; int pos = 0; int powerCnt = 0; try { if (s[pos] == '-') { pos++; negate = true; } if (s[pos++] != 'P') { goto error; } int count = _parseCount(s, ref pos); if (s[pos] == 'Y') { years = count; if (++pos == length) { goto success; } count = _parseCount(s, ref pos); } if (s[pos] == 'M') { months = count; if (++pos == length) { goto success; } count = _parseCount(s, ref pos); } if (s[pos] == 'D') { days = count; if (++pos == length) { goto success; } } if (s[pos] == 'T') { pos++; count = _parseCount(s, ref pos); if (s[pos] == 'H') { hours = count; if (++pos == length) { goto success; } count = _parseCount(s, ref pos); } if (s[pos] == 'M') { minutes = count; if (++pos == length) { goto success; } count = _parseCount(s, ref pos); } if (s[pos] == '.') { seconds = count; if (++pos == length) { goto error; } milliseconds = _parseCount(s, ref pos, ref powerCnt) / Math.Pow(10, powerCnt); if (s[pos] != 'S') { goto error; } if (++pos == length) { goto success; } } if (s[pos] == 'S') { seconds = count; if (++pos == length) { goto success; } } } if (pos != length) { goto error; } } catch (Exception) { goto error; } success: if (years == -1 || months == -1 || days == -1 || hours == -1 || minutes == -1 || seconds == -1) { goto error; } if (negate) { years *= -1; months *= -1; days *= -1; hours *= -1; minutes *= -1; seconds *= -1; milliseconds *= -1; } years += months / 12; months = months % 12; TimeSpan value = CreateTimeSpan(365 * years + 30 * months + days, hours, minutes, seconds, milliseconds * 1000); return(value); error: throw new FormatException(Res.GetString(Res.XmlConvert_BadTimeSpan)); }
/// <include file='doc\XmlEntity.uex' path='docs/doc[@for="XmlEntity.CloneNode"]/*' /> /// <devdoc> /// <para> /// Throws an excption since an entity can not be cloned. /// </para> /// </devdoc> public override XmlNode CloneNode(bool deep) { throw new InvalidOperationException(Res.GetString(Res.Xdom_Node_Cloning)); }