From: Krzysztof Wicher Date: Fri, 24 Jul 2020 23:18:45 +0000 (+0200) Subject: Nullable: System.Xml, part 5 (XmlDocument) (#39691) X-Git-Tag: submit/tizen/20210909.063632~6431 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=0e5614c1bcef4c744295c8ee4ddcd94a9ec8025a;p=platform%2Fupstream%2Fdotnet%2Fruntime.git Nullable: System.Xml, part 5 (XmlDocument) (#39691) * Nullable: System.Xml, part 5 (XmlDocument) * apply feedback --- diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs index 664014a..c7d02fa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs @@ -670,7 +670,7 @@ namespace System.Xml } } - public override string? GetAttribute(string name, string ns) + public override string? GetAttribute(string name, string? ns) { if (ScanState.XmlText == _state) { @@ -721,7 +721,7 @@ namespace System.Xml } } - public override bool MoveToAttribute(string name, string ns) + public override bool MoveToAttribute(string name, string? ns) { if (ScanState.XmlText == _state) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs index c9ddb2b..3f771d8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs @@ -10,6 +10,6 @@ namespace System.Xml internal partial interface IDtdParser { IDtdInfo ParseInternalDtd(IDtdParserAdapter adapter, bool saveInternalSubset); - IDtdInfo ParseFreeFloatingDtd(string baseUri, string docTypeName, string publicId, string systemId, string internalSubset, IDtdParserAdapter adapter); + IDtdInfo ParseFreeFloatingDtd(string baseUri, string docTypeName, string? publicId, string? systemId, string? internalSubset, IDtdParserAdapter adapter); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IRemovableWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IRemovableWriter.cs index b3e837f..c74dc52 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IRemovableWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IRemovableWriter.cs @@ -17,6 +17,6 @@ namespace System.Xml /// internal interface IRemovableWriter { - OnRemoveWriter OnRemoveWriterEvent { get; set; } + OnRemoveWriter? OnRemoveWriterEvent { get; set; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IValidationEventHandling.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IValidationEventHandling.cs index a19645a..57ce91b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IValidationEventHandling.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IValidationEventHandling.cs @@ -10,7 +10,7 @@ namespace System.Xml internal interface IValidationEventHandling { // This is a ValidationEventHandler, but it is not strongly typed due to dependencies on System.Xml.Schema - object EventHandler { get; } + object? EventHandler { get; } // The exception is XmlSchemaException, but it is not strongly typed due to dependencies on System.Xml.Schema void SendEvent(Exception exception, XmlSeverityType severity); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriter.cs index 9c631ed..6cced37 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriter.cs @@ -31,7 +31,7 @@ namespace System.Xml private readonly bool _checkWellFormedDoc; private bool _hasDocElem; private bool _inAttr; - private readonly string _systemId, _publicId; + private readonly string? _systemId, _publicId; private int _depth; public QueryOutputWriter(XmlRawWriter writer, XmlWriterSettings settings) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriterV1.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriterV1.cs index 8dd3f70..527c893 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriterV1.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriterV1.cs @@ -29,7 +29,7 @@ namespace System.Xml private readonly BitStack? _bitsCData; private readonly XmlQualifiedName? _qnameCData; private bool _outputDocType, _inAttr; - private readonly string _systemId, _publicId; + private readonly string? _systemId, _publicId; public QueryOutputWriterV1(XmlWriter writer, XmlWriterSettings settings) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs index 89c7c60..c58e0ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.IO; using System.Text; @@ -8,6 +9,7 @@ using System.Collections; using System.Xml.Schema; using System.Diagnostics; using System.Globalization; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -16,12 +18,12 @@ namespace System.Xml private string _localName; private string _namespaceUri; private string _prefix; - private string _nameWPrefix; + private string? _nameWPrefix; private string _rawValue; - private string _originalStringValue; // Original value + private string? _originalStringValue; // Original value private int _depth; - private AttributePSVIInfo _attributePSVIInfo; //Used only for default attributes + private AttributePSVIInfo? _attributePSVIInfo; //Used only for default attributes private XmlNodeType _nodeType; private int _lineNo; @@ -86,6 +88,7 @@ namespace System.Xml _nameWPrefix = nameTable.Add(string.Concat(_prefix, ":", _localName)); } } + return _nameWPrefix; } @@ -113,7 +116,7 @@ namespace System.Xml } } - public string OriginalStringValue + public string? OriginalStringValue { get { @@ -137,7 +140,7 @@ namespace System.Xml } } - public AttributePSVIInfo AttInfo + public AttributePSVIInfo? AttInfo { get { @@ -165,6 +168,10 @@ namespace System.Xml } } + [MemberNotNull(nameof(_localName))] + [MemberNotNull(nameof(_prefix))] + [MemberNotNull(nameof(_namespaceUri))] + [MemberNotNull(nameof(_rawValue))] internal void Clear(XmlNodeType nodeType) { _nodeType = nodeType; @@ -172,10 +179,12 @@ namespace System.Xml _prefix = string.Empty; _namespaceUri = string.Empty; _rawValue = string.Empty; + if (_attributePSVIInfo != null) { _attributePSVIInfo.Reset(); } + _nameWPrefix = null; _lineNo = 0; _linePos = 0; @@ -187,7 +196,7 @@ namespace System.Xml _linePos = linePos; } - internal void SetLineInfo(IXmlLineInfo lineInfo) + internal void SetLineInfo(IXmlLineInfo? lineInfo) { if (lineInfo != null) { @@ -210,7 +219,7 @@ namespace System.Xml SetItemData(value, value); } - internal void SetItemData(string value, string originalStringValue) + internal void SetItemData(string value, string? originalStringValue) { _rawValue = value; _originalStringValue = originalStringValue; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs index 1531dea..752e156 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; @@ -64,7 +65,7 @@ namespace System.Xml { get { - XmlReaderSettings settings = _coreReader.Settings; + XmlReaderSettings? settings = _coreReader.Settings; if (null != settings) { settings = settings.Clone(); @@ -151,7 +152,7 @@ namespace System.Xml } } - public override string BaseURI + public override string? BaseURI { get { @@ -205,7 +206,7 @@ namespace System.Xml } } - public override IXmlSchemaInfo SchemaInfo + public override IXmlSchemaInfo? SchemaInfo { get { @@ -418,13 +419,13 @@ namespace System.Xml } } - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { CheckAsync(); return _coreReader.GetAttribute(name); } - public override string GetAttribute(string name, string namespaceURI) + public override string? GetAttribute(string name, string? namespaceURI) { CheckAsync(); return _coreReader.GetAttribute(name, namespaceURI); @@ -445,7 +446,7 @@ namespace System.Xml } } - public override string this[string name] + public override string? this[string name] { get { @@ -460,7 +461,7 @@ namespace System.Xml return _coreReader.MoveToAttribute(name); } - public override bool MoveToAttribute(string name, string ns) + public override bool MoveToAttribute(string name, string? ns) { CheckAsync(); return _coreReader.MoveToAttribute(name, ns); @@ -541,7 +542,7 @@ namespace System.Xml } } - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { CheckAsync(); return _coreReader.LookupNamespace(prefix); @@ -754,7 +755,7 @@ namespace System.Xml _coreReader.Dispose(); } - internal override XmlNamespaceManager NamespaceManager + internal override XmlNamespaceManager? NamespaceManager { get { @@ -763,7 +764,7 @@ namespace System.Xml } } - internal override IDtdInfo DtdInfo + internal override IDtdInfo? DtdInfo { get { @@ -930,12 +931,12 @@ namespace System.Xml return _readerAsIXmlNamespaceResolver.GetNamespacesInScope(scope); } - string IXmlNamespaceResolver.LookupNamespace(string prefix) + string? IXmlNamespaceResolver.LookupNamespace(string prefix) { return _readerAsIXmlNamespaceResolver.LookupNamespace(prefix); } - string IXmlNamespaceResolver.LookupPrefix(string namespaceName) + string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _readerAsIXmlNamespaceResolver.LookupPrefix(namespaceName); } @@ -992,12 +993,12 @@ namespace System.Xml return _readerAsIXmlNamespaceResolver.GetNamespacesInScope(scope); } - string IXmlNamespaceResolver.LookupNamespace(string prefix) + string? IXmlNamespaceResolver.LookupNamespace(string prefix) { return _readerAsIXmlNamespaceResolver.LookupNamespace(prefix); } - string IXmlNamespaceResolver.LookupPrefix(string namespaceName) + string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _readerAsIXmlNamespaceResolver.LookupPrefix(namespaceName); } @@ -1014,7 +1015,6 @@ namespace System.Xml _readerAsIXmlSchemaInfo = (IXmlSchemaInfo)reader; } - #region IXmlSchemaInfo members XmlSchemaValidity IXmlSchemaInfo.Validity @@ -1041,7 +1041,7 @@ namespace System.Xml } } - XmlSchemaSimpleType IXmlSchemaInfo.MemberType + XmlSchemaSimpleType? IXmlSchemaInfo.MemberType { get { @@ -1049,7 +1049,7 @@ namespace System.Xml } } - XmlSchemaType IXmlSchemaInfo.SchemaType + XmlSchemaType? IXmlSchemaInfo.SchemaType { get { @@ -1057,7 +1057,7 @@ namespace System.Xml } } - XmlSchemaElement IXmlSchemaInfo.SchemaElement + XmlSchemaElement? IXmlSchemaInfo.SchemaElement { get { @@ -1065,7 +1065,7 @@ namespace System.Xml } } - XmlSchemaAttribute IXmlSchemaInfo.SchemaAttribute + XmlSchemaAttribute? IXmlSchemaInfo.SchemaAttribute { get { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs index 666fd54..84990c8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Threading.Tasks; using System.Xml.XPath; @@ -38,7 +39,7 @@ namespace System.Xml { get { - XmlWriterSettings settings = _coreWriter.Settings; + XmlWriterSettings? settings = _coreWriter.Settings; if (null != settings) { @@ -74,13 +75,13 @@ namespace System.Xml _coreWriter.WriteEndDocument(); } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { CheckAsync(); _coreWriter.WriteDocType(name, pubid, sysid, subset); } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { CheckAsync(); _coreWriter.WriteStartElement(prefix, localName, ns); @@ -98,7 +99,7 @@ namespace System.Xml _coreWriter.WriteFullEndElement(); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { CheckAsync(); _coreWriter.WriteStartAttribute(prefix, localName, ns); @@ -110,19 +111,19 @@ namespace System.Xml _coreWriter.WriteEndAttribute(); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { CheckAsync(); _coreWriter.WriteCData(text); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { CheckAsync(); _coreWriter.WriteComment(text); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { CheckAsync(); _coreWriter.WriteProcessingInstruction(name, text); @@ -140,13 +141,13 @@ namespace System.Xml _coreWriter.WriteCharEntity(ch); } - public override void WriteWhitespace(string ws) + public override void WriteWhitespace(string? ws) { CheckAsync(); _coreWriter.WriteWhitespace(ws); } - public override void WriteString(string text) + public override void WriteString(string? text) { CheckAsync(); _coreWriter.WriteString(text); @@ -209,7 +210,7 @@ namespace System.Xml _coreWriter.Flush(); } - public override string LookupPrefix(string ns) + public override string? LookupPrefix(string ns) { CheckAsync(); return _coreWriter.LookupPrefix(ns); @@ -224,7 +225,7 @@ namespace System.Xml } } - public override string XmlLang + public override string? XmlLang { get { @@ -245,7 +246,7 @@ namespace System.Xml _coreWriter.WriteName(name); } - public override void WriteQualifiedName(string localName, string ns) + public override void WriteQualifiedName(string localName, string? ns) { CheckAsync(); _coreWriter.WriteQualifiedName(localName, ns); @@ -257,7 +258,7 @@ namespace System.Xml _coreWriter.WriteValue(value); } - public override void WriteValue(string value) + public override void WriteValue(string? value) { CheckAsync(); _coreWriter.WriteValue(value); @@ -368,7 +369,7 @@ namespace System.Xml return task; } - public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) + public override Task WriteDocTypeAsync(string name, string? pubid, string? sysid, string? subset) { CheckAsync(); var task = _coreWriter.WriteDocTypeAsync(name, pubid, sysid, subset); @@ -376,7 +377,7 @@ namespace System.Xml return task; } - public override Task WriteStartElementAsync(string prefix, string localName, string ns) + public override Task WriteStartElementAsync(string? prefix, string localName, string? ns) { CheckAsync(); var task = _coreWriter.WriteStartElementAsync(prefix, localName, ns); @@ -400,7 +401,7 @@ namespace System.Xml return task; } - protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string ns) + protected internal override Task WriteStartAttributeAsync(string? prefix, string localName, string? ns) { CheckAsync(); var task = _coreWriter.WriteStartAttributeAsync(prefix, localName, ns); @@ -416,7 +417,7 @@ namespace System.Xml return task; } - public override Task WriteCDataAsync(string text) + public override Task WriteCDataAsync(string? text) { CheckAsync(); var task = _coreWriter.WriteCDataAsync(text); @@ -424,7 +425,7 @@ namespace System.Xml return task; } - public override Task WriteCommentAsync(string text) + public override Task WriteCommentAsync(string? text) { CheckAsync(); var task = _coreWriter.WriteCommentAsync(text); @@ -456,7 +457,7 @@ namespace System.Xml return task; } - public override Task WriteWhitespaceAsync(string ws) + public override Task WriteWhitespaceAsync(string? ws) { CheckAsync(); var task = _coreWriter.WriteWhitespaceAsync(ws); @@ -464,7 +465,7 @@ namespace System.Xml return task; } - public override Task WriteStringAsync(string text) + public override Task WriteStringAsync(string? text) { CheckAsync(); var task = _coreWriter.WriteStringAsync(text); @@ -544,7 +545,7 @@ namespace System.Xml return task; } - public override Task WriteQualifiedNameAsync(string localName, string ns) + public override Task WriteQualifiedNameAsync(string localName, string? ns) { CheckAsync(); var task = _coreWriter.WriteQualifiedNameAsync(localName, ns); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAutoDetectWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAutoDetectWriter.cs index c4cf2e9..c3aa8c0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAutoDetectWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAutoDetectWriter.cs @@ -1,10 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { using System; using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Xml; @@ -17,12 +19,12 @@ namespace System.Xml /// internal class XmlAutoDetectWriter : XmlRawWriter, IRemovableWriter { - private XmlRawWriter _wrapped; - private OnRemoveWriter _onRemove; + private XmlRawWriter? _wrapped; + private OnRemoveWriter? _onRemove; private readonly XmlWriterSettings _writerSettings; private readonly XmlEventCache _eventCache; // Cache up events until first StartElement is encountered - private readonly TextWriter _textWriter; - private readonly Stream _strm; + private readonly TextWriter? _textWriter; + private readonly Stream? _strm; //----------------------------------------------- // Constructors @@ -59,7 +61,7 @@ namespace System.Xml /// /// This writer will raise this event once it has determined whether to replace itself with the Html or Xml writer. /// - public OnRemoveWriter OnRemoveWriterEvent + public OnRemoveWriter? OnRemoveWriterEvent { get { return _onRemove; } set { _onRemove = value; } @@ -75,26 +77,27 @@ namespace System.Xml get { return _writerSettings; } } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { EnsureWrappedWriter(XmlOutputMethod.Xml); _wrapped.WriteDocType(name, pubid, sysid, subset); } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { if (_wrapped == null) { // This is the first time WriteStartElement has been called, so create the Xml or Html writer - if (ns.Length == 0 && IsHtmlTag(localName)) + if (ns!.Length == 0 && IsHtmlTag(localName)) CreateWrappedWriter(XmlOutputMethod.Html); else CreateWrappedWriter(XmlOutputMethod.Xml); } + _wrapped.WriteStartElement(prefix, localName, ns); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { EnsureWrappedWriter(XmlOutputMethod.Xml); _wrapped.WriteStartAttribute(prefix, localName, ns); @@ -106,7 +109,7 @@ namespace System.Xml _wrapped.WriteEndAttribute(); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { if (TextBlockCreatesWriter(text)) _wrapped.WriteCData(text); @@ -114,7 +117,7 @@ namespace System.Xml _eventCache.WriteCData(text); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { if (_wrapped == null) _eventCache.WriteComment(text); @@ -122,7 +125,7 @@ namespace System.Xml _wrapped.WriteComment(text); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { if (_wrapped == null) _eventCache.WriteProcessingInstruction(name, text); @@ -130,7 +133,7 @@ namespace System.Xml _wrapped.WriteProcessingInstruction(name, text); } - public override void WriteWhitespace(string ws) + public override void WriteWhitespace(string? ws) { if (_wrapped == null) _eventCache.WriteWhitespace(ws); @@ -138,7 +141,7 @@ namespace System.Xml _wrapped.WriteWhitespace(ws); } - public override void WriteString(string text) + public override void WriteString(string? text) { if (TextBlockCreatesWriter(text)) _wrapped.WriteString(text); @@ -214,7 +217,7 @@ namespace System.Xml _wrapped.WriteValue(value); } - public override void WriteValue(string value) + public override void WriteValue(string? value) { EnsureWrappedWriter(XmlOutputMethod.Xml); _wrapped.WriteValue(value); @@ -272,7 +275,7 @@ namespace System.Xml // XmlRawWriter interface //----------------------------------------------- - internal override IXmlNamespaceResolver NamespaceResolver + internal override IXmlNamespaceResolver? NamespaceResolver { get { @@ -331,7 +334,7 @@ namespace System.Xml { get { - return _wrapped.SupportsNamespaceDeclarationInChunks; + return _wrapped!.SupportsNamespaceDeclarationInChunks; } } @@ -343,7 +346,7 @@ namespace System.Xml internal override void WriteEndNamespaceDeclaration() { - _wrapped.WriteEndNamespaceDeclaration(); + _wrapped!.WriteEndNamespaceDeclaration(); } //----------------------------------------------- @@ -376,6 +379,7 @@ namespace System.Xml /// /// If a wrapped writer has not yet been created, create one. /// + [MemberNotNull(nameof(_wrapped))] private void EnsureWrappedWriter(XmlOutputMethod outMethod) { if (_wrapped == null) @@ -387,7 +391,8 @@ namespace System.Xml /// force the creation of a wrapped writer. Otherwise, create a wrapped writer if one has not yet been /// created and return true. /// - private bool TextBlockCreatesWriter(string textBlock) + [MemberNotNullWhen(true, nameof(_wrapped))] + private bool TextBlockCreatesWriter(string? textBlock) { if (_wrapped == null) { @@ -407,6 +412,7 @@ namespace System.Xml /// /// Create either the Html or Xml writer and send any cached events to it. /// + [MemberNotNull(nameof(_wrapped))] private void CreateWrappedWriter(XmlOutputMethod outMethod) { Debug.Assert(_wrapped == null); @@ -422,9 +428,9 @@ namespace System.Xml _writerSettings.ReadOnly = true; if (_textWriter != null) - _wrapped = ((XmlWellFormedWriter)XmlWriter.Create(_textWriter, _writerSettings)).RawWriter; + _wrapped = ((XmlWellFormedWriter)XmlWriter.Create(_textWriter, _writerSettings)).RawWriter!; else - _wrapped = ((XmlWellFormedWriter)XmlWriter.Create(_strm, _writerSettings)).RawWriter; + _wrapped = ((XmlWellFormedWriter)XmlWriter.Create(_strm!, _writerSettings)).RawWriter!; // Send cached events to the new writer _eventCache.EndEvents(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs index 7dadd48..ca0ce55 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs @@ -119,7 +119,7 @@ namespace System.Xml return base.reader.MoveToAttribute(name); } - public override bool MoveToAttribute(string name, string ns) + public override bool MoveToAttribute(string name, string? ns) { if (_state == State.InReadBinary) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs index 387d182..68f79ba 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml; using System.Diagnostics; @@ -162,8 +163,7 @@ namespace System.Xml ValidateQName(base.reader.Name); CheckCharacters(base.reader.Value); - string str; - str = base.reader.GetAttribute("SYSTEM"); + string? str = base.reader.GetAttribute("SYSTEM"); if (str != null) { CheckCharacters(str); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs index e8f8fad..2fa82a6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs @@ -1,12 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.IO; using System.Text; using System.Xml.Schema; using System.Collections; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -50,30 +52,33 @@ namespace System.Xml { get { - XmlWriterSettings s = base.writer.Settings; + XmlWriterSettings? s = base.writer.Settings; s = (s != null) ? (XmlWriterSettings)s.Clone() : new XmlWriterSettings(); if (_checkValues) { s.CheckCharacters = true; } + if (_replaceNewLines) { s.NewLineHandling = NewLineHandling.Replace; s.NewLineChars = _newLineChars; } + s.ReadOnly = true; return s; } } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { if (_checkNames) { ValidateQName(name); } + if (_checkValues) { if (pubid != null) @@ -84,25 +89,29 @@ namespace System.Xml throw XmlConvert.CreateInvalidCharException(pubid, i); } } + if (sysid != null) { CheckCharacters(sysid); } + if (subset != null) { CheckCharacters(subset); } } + if (_replaceNewLines) { sysid = ReplaceNewLines(sysid); pubid = ReplaceNewLines(pubid); subset = ReplaceNewLines(subset); } + writer.WriteDocType(name, pubid, sysid, subset); } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { if (_checkNames) { @@ -110,6 +119,7 @@ namespace System.Xml { throw new ArgumentException(SR.Xml_EmptyLocalName); } + ValidateNCName(localName); if (prefix != null && prefix.Length > 0) @@ -117,10 +127,11 @@ namespace System.Xml ValidateNCName(prefix); } } + writer.WriteStartElement(prefix, localName, ns); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { if (_checkNames) { @@ -128,6 +139,7 @@ namespace System.Xml { throw new ArgumentException(SR.Xml_EmptyLocalName); } + ValidateNCName(localName); if (prefix != null && prefix.Length > 0) @@ -135,10 +147,11 @@ namespace System.Xml ValidateNCName(prefix); } } + writer.WriteStartAttribute(prefix, localName, ns); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { if (text != null) { @@ -146,10 +159,12 @@ namespace System.Xml { CheckCharacters(text); } + if (_replaceNewLines) { text = ReplaceNewLines(text); } + int i; while ((i = text.IndexOf("]]>", StringComparison.Ordinal)) >= 0) { @@ -160,7 +175,7 @@ namespace System.Xml writer.WriteCData(text); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { if (text != null) { @@ -169,20 +184,23 @@ namespace System.Xml CheckCharacters(text); text = InterleaveInvalidChars(text, '-', '-'); } + if (_replaceNewLines) { text = ReplaceNewLines(text); } } + writer.WriteComment(text); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { if (_checkNames) { ValidateNCName(name); } + if (text != null) { if (_checkValues) @@ -190,11 +208,13 @@ namespace System.Xml CheckCharacters(text); text = InterleaveInvalidChars(text, '?', '>'); } + if (_replaceNewLines) { text = ReplaceNewLines(text); } } + writer.WriteProcessingInstruction(name, text); } @@ -204,15 +224,17 @@ namespace System.Xml { ValidateQName(name); } + writer.WriteEntityRef(name); } - public override void WriteWhitespace(string ws) + public override void WriteWhitespace(string? ws) { if (ws == null) { ws = string.Empty; } + // "checkNames" is intentional here; if false, the whitespace is checked in XmlWellformedWriter if (_checkNames) { @@ -222,14 +244,16 @@ namespace System.Xml throw new ArgumentException(SR.Format(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(ws, i))); } } + if (_replaceNewLines) { ws = ReplaceNewLines(ws); } + writer.WriteWhitespace(ws); } - public override void WriteString(string text) + public override void WriteString(string? text) { if (text != null) { @@ -242,6 +266,7 @@ namespace System.Xml text = ReplaceNewLines(text); } } + writer.WriteString(text); } @@ -273,15 +298,17 @@ namespace System.Xml { CheckCharacters(buffer, index, count); } + if (_replaceNewLines && WriteState != WriteState.Attribute) { - string text = ReplaceNewLines(buffer, index, count); + string? text = ReplaceNewLines(buffer, index, count); if (text != null) { WriteString(text); return; } } + writer.WriteChars(buffer, index, count); } @@ -293,8 +320,10 @@ namespace System.Xml { throw new ArgumentException(SR.Xml_EmptyName); } + XmlConvert.VerifyNMTOKEN(name); } + writer.WriteNmToken(name); } @@ -304,15 +333,17 @@ namespace System.Xml { XmlConvert.VerifyQName(name, ExceptionType.XmlException); } + writer.WriteName(name); } - public override void WriteQualifiedName(string localName, string ns) + public override void WriteQualifiedName(string localName, string? ns) { if (_checkNames) { ValidateNCName(localName); } + writer.WriteQualifiedName(localName, ns); } @@ -349,6 +380,7 @@ namespace System.Xml { throw new ArgumentException(SR.Xml_EmptyName); } + int colonPos; int len = ValidateNames.ParseQName(name, 0, out colonPos); if (len != name.Length) @@ -358,14 +390,15 @@ namespace System.Xml } } - private string ReplaceNewLines(string str) + [return: NotNullIfNotNull("str")] + private string? ReplaceNewLines(string? str) { if (str == null) { return null; } - StringBuilder sb = null; + StringBuilder? sb = null; int start = 0; int i; for (i = 0; i < str.Length; i++) @@ -396,10 +429,12 @@ namespace System.Xml i++; continue; } + if (sb == null) { sb = new StringBuilder(str.Length + 5); } + sb.Append(str, start, i - start); i++; } @@ -409,10 +444,12 @@ namespace System.Xml { continue; } + if (sb == null) { sb = new StringBuilder(str.Length + 5); } + sb.Append(str, start, i - start); } } @@ -435,14 +472,14 @@ namespace System.Xml } } - private string ReplaceNewLines(char[] data, int offset, int len) + private string? ReplaceNewLines(char[]? data, int offset, int len) { if (data == null) { return null; } - StringBuilder sb = null; + StringBuilder? sb = null; int start = offset; int endPos = offset + len; int i; @@ -453,16 +490,19 @@ namespace System.Xml { continue; } + if (ch == '\n') { if (_newLineChars == "\n") { continue; } + if (sb == null) { sb = new StringBuilder(len + 5); } + sb.Append(data, start, i - start); } else if (ch == '\r') @@ -474,10 +514,12 @@ namespace System.Xml i++; continue; } + if (sb == null) { sb = new StringBuilder(len + 5); } + sb.Append(data, start, i - start); i++; } @@ -487,10 +529,12 @@ namespace System.Xml { continue; } + if (sb == null) { sb = new StringBuilder(len + 5); } + sb.Append(data, start, i - start); } } @@ -498,6 +542,7 @@ namespace System.Xml { continue; } + sb.Append(_newLineChars); start = i + 1; } @@ -518,7 +563,7 @@ namespace System.Xml // Any "?>" in PI value must be replaced with "? >". private string InterleaveInvalidChars(string text, char invChar1, char invChar2) { - StringBuilder sb = null; + StringBuilder? sb = null; int start = 0; int i; for (i = 0; i < text.Length; i++) @@ -533,6 +578,7 @@ namespace System.Xml { sb = new StringBuilder(text.Length + 5); } + sb.Append(text, start, i - start); sb.Append(' '); start = i; @@ -551,6 +597,7 @@ namespace System.Xml { sb.Append(' '); } + return sb.ToString(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs index 722d1d7..4b5a0e9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.IO; using System.Text; @@ -17,12 +18,13 @@ namespace System.Xml // internal partial class XmlCharCheckingWriter : XmlWrappingWriter { - public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) + public override Task WriteDocTypeAsync(string name, string? pubid, string? sysid, string? subset) { if (_checkNames) { ValidateQName(name); } + if (_checkValues) { if (pubid != null) @@ -33,25 +35,29 @@ namespace System.Xml throw XmlConvert.CreateInvalidCharException(pubid, i); } } + if (sysid != null) { CheckCharacters(sysid); } + if (subset != null) { CheckCharacters(subset); } } + if (_replaceNewLines) { sysid = ReplaceNewLines(sysid); pubid = ReplaceNewLines(pubid); subset = ReplaceNewLines(subset); } + return writer.WriteDocTypeAsync(name, pubid, sysid, subset); } - public override Task WriteStartElementAsync(string prefix, string localName, string ns) + public override Task WriteStartElementAsync(string? prefix, string localName, string? ns) { if (_checkNames) { @@ -59,6 +65,7 @@ namespace System.Xml { throw new ArgumentException(SR.Xml_EmptyLocalName); } + ValidateNCName(localName); if (prefix != null && prefix.Length > 0) @@ -69,7 +76,7 @@ namespace System.Xml return writer.WriteStartElementAsync(prefix, localName, ns); } - protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string ns) + protected internal override Task WriteStartAttributeAsync(string? prefix, string localName, string? ns) { if (_checkNames) { @@ -77,6 +84,7 @@ namespace System.Xml { throw new ArgumentException(SR.Xml_EmptyLocalName); } + ValidateNCName(localName); if (prefix != null && prefix.Length > 0) @@ -84,10 +92,11 @@ namespace System.Xml ValidateNCName(prefix); } } + return writer.WriteStartAttributeAsync(prefix, localName, ns); } - public override async Task WriteCDataAsync(string text) + public override async Task WriteCDataAsync(string? text) { if (text != null) { @@ -95,10 +104,12 @@ namespace System.Xml { CheckCharacters(text); } + if (_replaceNewLines) { text = ReplaceNewLines(text); } + int i; while ((i = text.IndexOf("]]>", StringComparison.Ordinal)) >= 0) { @@ -106,10 +117,11 @@ namespace System.Xml text = text.Substring(i + 2); } } + await writer.WriteCDataAsync(text).ConfigureAwait(false); } - public override Task WriteCommentAsync(string text) + public override Task WriteCommentAsync(string? text) { if (text != null) { @@ -132,6 +144,7 @@ namespace System.Xml { ValidateNCName(name); } + if (text != null) { if (_checkValues) @@ -144,7 +157,8 @@ namespace System.Xml text = ReplaceNewLines(text); } } - return writer.WriteProcessingInstructionAsync(name, text); + + return writer.WriteProcessingInstructionAsync(name, text!); } public override Task WriteEntityRefAsync(string name) @@ -156,12 +170,13 @@ namespace System.Xml return writer.WriteEntityRefAsync(name); } - public override Task WriteWhitespaceAsync(string ws) + public override Task WriteWhitespaceAsync(string? ws) { if (ws == null) { ws = string.Empty; } + // "checkNames" is intentional here; if false, the whitespace is checked in XmlWellformedWriter if (_checkNames) { @@ -171,14 +186,16 @@ namespace System.Xml throw new ArgumentException(SR.Format(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(ws, i))); } } + if (_replaceNewLines) { ws = ReplaceNewLines(ws); } + return writer.WriteWhitespaceAsync(ws); } - public override Task WriteStringAsync(string text) + public override Task WriteStringAsync(string? text) { if (text != null) { @@ -186,11 +203,13 @@ namespace System.Xml { CheckCharacters(text); } + if (_replaceNewLines && WriteState != WriteState.Attribute) { text = ReplaceNewLines(text); } } + return writer.WriteStringAsync(text); } @@ -222,14 +241,16 @@ namespace System.Xml { CheckCharacters(buffer, index, count); } + if (_replaceNewLines && WriteState != WriteState.Attribute) { - string text = ReplaceNewLines(buffer, index, count); + string? text = ReplaceNewLines(buffer, index, count); if (text != null) { return WriteStringAsync(text); } } + return writer.WriteCharsAsync(buffer, index, count); } @@ -255,12 +276,13 @@ namespace System.Xml return writer.WriteNameAsync(name); } - public override Task WriteQualifiedNameAsync(string localName, string ns) + public override Task WriteQualifiedNameAsync(string localName, string? ns) { if (_checkNames) { ValidateNCName(localName); } + return writer.WriteQualifiedNameAsync(localName, ns); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs index 7456b44..fe8091c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs @@ -107,7 +107,7 @@ namespace System.Xml } // Forward call to WriteString(string). - public override Task WriteCDataAsync(string text) + public override Task WriteCDataAsync(string? text) { return WriteStringAsync(text); } @@ -126,7 +126,7 @@ namespace System.Xml } // Forward call to WriteString(string). - public override Task WriteWhitespaceAsync(string ws) + public override Task WriteWhitespaceAsync(string? ws) { return WriteStringAsync(ws); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs index 258f4b5..36abf85 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs @@ -620,7 +620,7 @@ namespace System.Xml public abstract string? GetAttribute(string name); // Gets the value of the attribute with the LocalName and NamespaceURI - public abstract string? GetAttribute(string name, string namespaceURI); + public abstract string? GetAttribute(string name, string? namespaceURI); // Gets the value of the attribute with the specified index. public abstract string GetAttribute(int i); @@ -644,7 +644,7 @@ namespace System.Xml } // Gets the value of the attribute with the LocalName and NamespaceURI - public virtual string? this[string name, string namespaceURI] + public virtual string? this[string name, string? namespaceURI] { get { @@ -656,7 +656,7 @@ namespace System.Xml public abstract bool MoveToAttribute(string name); // Moves to the attribute with the specified LocalName and NamespaceURI. - public abstract bool MoveToAttribute(string name, string ns); + public abstract bool MoveToAttribute(string name, string? ns); // Moves to the attribute with the specified index. public virtual void MoveToAttribute(int i) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs index 5d7f5db..d00bc27 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs @@ -265,7 +265,7 @@ namespace System.Xml return null; } - public override string? GetAttribute(string name, string namespaceURI) + public override string? GetAttribute(string name, string? namespaceURI) { if (!InAttributeActiveState) { @@ -334,7 +334,7 @@ namespace System.Xml return false; } - public override bool MoveToAttribute(string name, string ns) + public override bool MoveToAttribute(string name, string? ns) { if (!InAttributeActiveState) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs index 5e1b4d9..4859829 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs @@ -83,13 +83,13 @@ namespace System.Xml _impl.OuterReader = this; } - public XmlTextReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context) + public XmlTextReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext? context) { _impl = new XmlTextReaderImpl(xmlFragment, fragType, context); _impl.OuterReader = this; } - public XmlTextReader(string xmlFragment, XmlNodeType fragType, XmlParserContext context) + public XmlTextReader(string xmlFragment, XmlNodeType fragType, XmlParserContext? context) { _impl = new XmlTextReaderImpl(xmlFragment, fragType, context); _impl.OuterReader = this; @@ -203,7 +203,7 @@ namespace System.Xml return _impl.MoveToAttribute(name); } - public override bool MoveToAttribute(string localName, string namespaceURI) + public override bool MoveToAttribute(string localName, string? namespaceURI) { return _impl.MoveToAttribute(localName, namespaceURI); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index 4a959c2..32c82f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -506,7 +506,7 @@ namespace System.Xml // Initializes a new instance of XmlTextReaderImpl class for parsing fragments with the specified stream, fragment type and parser context // This constructor is used when creating XmlTextReaderImpl for V1 XmlTextReader // SxS: The method resolves URI but does not expose the resolved value up the stack hence Resource Exposure scope is None. - internal XmlTextReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context) + internal XmlTextReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext? context) : this((context != null && context.NameTable != null) ? context.NameTable : new NameTable()) { Encoding? enc = (context != null) ? context.Encoding : null; @@ -529,7 +529,7 @@ namespace System.Xml // Initializes a new instance of XmlTextRreaderImpl class for parsing fragments with the specified string, fragment type and parser context // This constructor is used when creating XmlTextReaderImpl for V1 XmlTextReader - internal XmlTextReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext context) + internal XmlTextReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext? context) : this(null == context || null == context.NameTable ? new NameTable() : context.NameTable) { if (xmlFragment == null) @@ -556,7 +556,7 @@ namespace System.Xml // "innerXml" of an XmlDecl is. This internal function is required by DOM. When(if) we handle/allow // all nodetypes in InnerXml then we should support them as part of fragment constructor as well. // Until then, this internal function will have to do. - internal XmlTextReaderImpl(string xmlFragment, XmlParserContext context) + internal XmlTextReaderImpl(string xmlFragment, XmlParserContext? context) : this(null == context || null == context.NameTable ? new NameTable() : context.NameTable) { InitStringInput((context == null) ? string.Empty : context.BaseURI, Encoding.Unicode, string.Concat("")); @@ -821,7 +821,7 @@ namespace System.Xml // Initializes a new instance of the XmlTextReaderImpl class for fragment parsing. // This constructor is used by XmlBinaryReader for nested text XML - internal XmlTextReaderImpl(string xmlFragment, XmlParserContext context, XmlReaderSettings settings) + internal XmlTextReaderImpl(string xmlFragment, XmlParserContext? context, XmlReaderSettings settings) : this(null, settings, context) { Debug.Assert(xmlFragment != null); @@ -9247,7 +9247,7 @@ namespace System.Xml // Validation support // - internal IValidationEventHandling ValidationEventHandling + internal IValidationEventHandling? ValidationEventHandling { set { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs index 38e7b86..a50f7da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs @@ -293,7 +293,7 @@ namespace System.Xml } // Creates an instance of the XmlTextWriter class using the specified file. - public XmlTextWriter(string filename, Encoding encoding) + public XmlTextWriter(string filename, Encoding? encoding) : this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), encoding) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs index c0c9b77..a3911c8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.IO; using System.Text; @@ -17,6 +18,7 @@ namespace System.Xml // Member fields // private readonly XmlValidatingReaderImpl _impl; + // // Constructors // @@ -32,6 +34,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(xmlFragment)); } + _impl = new XmlValidatingReaderImpl(xmlFragment, fragType, context); _impl.OuterReader = this; } @@ -89,7 +92,7 @@ namespace System.Xml get { return _impl.Depth; } } - public override string BaseURI + public override string? BaseURI { get { return _impl.BaseURI; } } @@ -123,12 +126,12 @@ namespace System.Xml public override int AttributeCount { get { return _impl.AttributeCount; } } - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { return _impl.GetAttribute(name); } - public override string GetAttribute(string localName, string namespaceURI) + public override string? GetAttribute(string localName, string? namespaceURI) { return _impl.GetAttribute(localName, namespaceURI); } @@ -143,7 +146,7 @@ namespace System.Xml return _impl.MoveToAttribute(name); } - public override bool MoveToAttribute(string localName, string namespaceURI) + public override bool MoveToAttribute(string localName, string? namespaceURI) { return _impl.MoveToAttribute(localName, namespaceURI); } @@ -198,13 +201,14 @@ namespace System.Xml get { return _impl.NameTable; } } - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { - string ns = _impl.LookupNamespace(prefix); + string? ns = _impl.LookupNamespace(prefix); if (ns != null && ns.Length == 0) { ns = null; } + return ns; } @@ -269,12 +273,12 @@ namespace System.Xml return _impl.GetNamespacesInScope(scope); } - string IXmlNamespaceResolver.LookupNamespace(string prefix) + string? IXmlNamespaceResolver.LookupNamespace(string prefix) { return _impl.LookupNamespace(prefix); } - string IXmlNamespaceResolver.LookupPrefix(string namespaceName) + string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _impl.LookupPrefix(namespaceName); } @@ -288,7 +292,7 @@ namespace System.Xml remove { _impl.ValidationEventHandler -= value; } } - public object SchemaType + public object? SchemaType { get { return _impl.SchemaType; } } @@ -326,12 +330,12 @@ namespace System.Xml set { _impl.Namespaces = value; } } - public object ReadTypedValue() + public object? ReadTypedValue() { return _impl.ReadTypedValue(); } - public Encoding Encoding + public Encoding? Encoding { get { return _impl.Encoding; } } @@ -343,7 +347,7 @@ namespace System.Xml get { return _impl; } } - internal override IDtdInfo DtdInfo + internal override IDtdInfo? DtdInfo { get { return _impl.DtdInfo; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs index e8a6944..239b854 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.IO; using System.Text; @@ -10,6 +11,7 @@ using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.Versioning; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -35,7 +37,7 @@ namespace System.Xml { // Fields private readonly XmlValidatingReaderImpl _reader; - private ValidationEventHandler _eventHandler; + private ValidationEventHandler? _eventHandler; // Constructor internal ValidationEventHandling(XmlValidatingReaderImpl reader) @@ -45,7 +47,7 @@ namespace System.Xml // IValidationEventHandling interface #region IValidationEventHandling interface - object IValidationEventHandling.EventHandler + object? IValidationEventHandling.EventHandler { get { return _eventHandler; } } @@ -81,7 +83,7 @@ namespace System.Xml // core text reader private readonly XmlReader _coreReader; private readonly XmlTextReaderImpl _coreReaderImpl; - private readonly IXmlNamespaceResolver _coreReaderNSResolver; + private readonly IXmlNamespaceResolver? _coreReaderNSResolver; // validation private ValidationType _validationType; @@ -99,10 +101,10 @@ namespace System.Xml private readonly ValidationEventHandling _eventHandling; // misc - private readonly XmlParserContext _parserContext; + private readonly XmlParserContext? _parserContext; // helper for Read[Element]ContentAs{Base64,BinHex} methods - private ReadContentAsBinaryHelper _readBinaryHelper; + private ReadContentAsBinaryHelper? _readBinaryHelper; // Outer XmlReader exposed to the user - either XmlValidatingReader or XmlValidatingReaderImpl (when created via XmlReader.Create). // Virtual methods called from within XmlValidatingReaderImpl must be called on the outer reader so in case the user overrides @@ -116,27 +118,30 @@ namespace System.Xml // This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader internal XmlValidatingReaderImpl(XmlReader reader) { - XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader; + XmlAsyncCheckReader? asyncCheckReader = reader as XmlAsyncCheckReader; if (asyncCheckReader != null) { reader = asyncCheckReader.CoreReader; } + _outerReader = this; _coreReader = reader; _coreReaderNSResolver = reader as IXmlNamespaceResolver; - _coreReaderImpl = reader as XmlTextReaderImpl; + _coreReaderImpl = (reader as XmlTextReaderImpl)!; if (_coreReaderImpl == null) { - XmlTextReader tr = reader as XmlTextReader; + XmlTextReader? tr = reader as XmlTextReader; if (tr != null) { _coreReaderImpl = tr.Impl; } } + if (_coreReaderImpl == null) { throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, nameof(reader)); } + _coreReaderImpl.EntityHandling = EntityHandling.ExpandEntities; _coreReaderImpl.XmlValidatingReaderCompatibilityMode = true; _processIdentityConstraints = true; @@ -152,18 +157,17 @@ namespace System.Xml _validationType = ValidationType.Auto; SetupValidation(ValidationType.Auto); #pragma warning restore 618 - } // Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified string, 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(string xmlFragment, XmlNodeType fragType, XmlParserContext context) + internal XmlValidatingReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext? context) : this(new XmlTextReader(xmlFragment, fragType, context)) { - if (_coreReader.BaseURI.Length > 0) + if (_coreReader.BaseURI!.Length > 0) { - _validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI); + _validator.BaseUri = GetResolver()!.ResolveUri(null, _coreReader.BaseURI); } if (context != null) @@ -176,12 +180,12 @@ namespace System.Xml // 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) + internal XmlValidatingReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext? context) : this(new XmlTextReader(xmlFragment, fragType, context)) { - if (_coreReader.BaseURI.Length > 0) + if (_coreReader.BaseURI!.Length > 0) { - _validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI); + _validator.BaseUri = GetResolver()!.ResolveUri(null, _coreReader.BaseURI); } if (context != null) @@ -193,28 +197,31 @@ namespace System.Xml // Initializes a new instance of XmlValidatingReaderImpl class with the specified arguments. // This constructor is used when creating XmlValidatingReaderImpl reader via "XmlReader.Create(..)" - internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler settingsEventHandler, bool processIdentityConstraints) + internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler? settingsEventHandler, bool processIdentityConstraints) { - XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader; + XmlAsyncCheckReader? asyncCheckReader = reader as XmlAsyncCheckReader; if (asyncCheckReader != null) { reader = asyncCheckReader.CoreReader; } + _outerReader = this; _coreReader = reader; - _coreReaderImpl = reader as XmlTextReaderImpl; + _coreReaderImpl = (reader as XmlTextReaderImpl)!; if (_coreReaderImpl == null) { - XmlTextReader tr = reader as XmlTextReader; + XmlTextReader? tr = reader as XmlTextReader; if (tr != null) { _coreReaderImpl = tr.Impl; } } + if (_coreReaderImpl == null) { throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, nameof(reader)); } + _coreReaderImpl.XmlValidatingReaderCompatibilityMode = true; _coreReaderNSResolver = reader as IXmlNamespaceResolver; _processIdentityConstraints = processIdentityConstraints; @@ -243,11 +250,11 @@ namespace System.Xml // XmlReader members // // Returns the current settings of the reader - public override XmlReaderSettings Settings + public override XmlReaderSettings? Settings { get { - XmlReaderSettings settings; + XmlReaderSettings? settings; if (_coreReaderImpl.V1Compat) { settings = null; @@ -256,6 +263,7 @@ namespace System.Xml { settings = _coreReader.Settings; } + if (settings != null) { settings = settings.Clone(); @@ -264,11 +272,13 @@ namespace System.Xml { settings = new XmlReaderSettings(); } + settings.ValidationType = ValidationType.DTD; if (!_processIdentityConstraints) { settings.ValidationFlags &= ~XmlSchemaValidationFlags.ProcessIdentityConstraints; } + settings.ReadOnly = true; return settings; } @@ -347,7 +357,7 @@ namespace System.Xml } // Returns the base URI of the current node. - public override string BaseURI + public override string? BaseURI { get { @@ -428,7 +438,7 @@ namespace System.Xml } // Returns encoding of the XML document - internal Encoding Encoding + internal Encoding? Encoding { get { @@ -446,13 +456,13 @@ namespace System.Xml } // Returns value of an attribute with the specified Name - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { return _coreReader.GetAttribute(name); } // Returns value of an attribute with the specified LocalName and NamespaceURI - public override string GetAttribute(string localName, string namespaceURI) + public override string? GetAttribute(string localName, string? namespaceURI) { return _coreReader.GetAttribute(localName, namespaceURI); } @@ -475,7 +485,7 @@ namespace System.Xml } // Moves to an attribute with the specified LocalName and NamespceURI - public override bool MoveToAttribute(string localName, string namespaceURI) + public override bool MoveToAttribute(string localName, string? namespaceURI) { if (!_coreReader.MoveToAttribute(localName, namespaceURI)) { @@ -565,7 +575,7 @@ namespace System.Xml goto case ParsingFunction.Read; case ParsingFunction.InReadBinaryContent: _parsingFunction = ParsingFunction.Read; - _readBinaryHelper.Finish(); + _readBinaryHelper!.Finish(); goto case ParsingFunction.Read; default: Debug.Fail($"Unexpected parsing function {_parsingFunction}"); @@ -581,7 +591,7 @@ namespace System.Xml } // Returns NamespaceURI associated with the specified prefix in the current namespace scope. - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { return _coreReaderImpl.LookupNamespace(prefix); } @@ -592,7 +602,7 @@ namespace System.Xml if (_parsingFunction == ParsingFunction.InReadBinaryContent) { _parsingFunction = ParsingFunction.Read; - _readBinaryHelper.Finish(); + _readBinaryHelper!.Finish(); } if (!_coreReader.ReadAttributeValue()) { @@ -627,7 +637,7 @@ namespace System.Xml _parsingFunction = ParsingFunction.Read; // call to the helper - int readCount = _readBinaryHelper.ReadContentAsBase64(buffer, index, count); + int readCount = _readBinaryHelper!.ReadContentAsBase64(buffer, index, count); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; @@ -651,7 +661,7 @@ namespace System.Xml _parsingFunction = ParsingFunction.Read; // call to the helper - int readCount = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count); + int readCount = _readBinaryHelper!.ReadContentAsBinHex(buffer, index, count); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; @@ -675,7 +685,7 @@ namespace System.Xml _parsingFunction = ParsingFunction.Read; // call to the helper - int readCount = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count); + int readCount = _readBinaryHelper!.ReadElementContentAsBase64(buffer, index, count); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; @@ -699,7 +709,7 @@ namespace System.Xml _parsingFunction = ParsingFunction.Read; // call to the helper - int readCount = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count); + int readCount = _readBinaryHelper!.ReadElementContentAsBinHex(buffer, index, count); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; @@ -791,12 +801,12 @@ namespace System.Xml return this.GetNamespacesInScope(scope); } - string IXmlNamespaceResolver.LookupNamespace(string prefix) + string? IXmlNamespaceResolver.LookupNamespace(string prefix) { return this.LookupNamespace(prefix); } - string IXmlNamespaceResolver.LookupPrefix(string namespaceName) + string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return this.LookupPrefix(namespaceName); } @@ -804,12 +814,12 @@ namespace System.Xml // Internal IXmlNamespaceResolver methods internal IDictionary GetNamespacesInScope(XmlNamespaceScope scope) { - return _coreReaderNSResolver.GetNamespacesInScope(scope); + return _coreReaderNSResolver!.GetNamespacesInScope(scope); } - internal string LookupPrefix(string namespaceName) + internal string? LookupPrefix(string namespaceName) { - return _coreReaderNSResolver.LookupPrefix(namespaceName); + return _coreReaderNSResolver!.LookupPrefix(namespaceName); } // @@ -829,17 +839,18 @@ namespace System.Xml } // returns the schema type of the current node - internal object SchemaType + internal object? SchemaType { get { if (_validationType != ValidationType.None) { - XmlSchemaType schemaTypeObj = _coreReaderImpl.InternalSchemaType as XmlSchemaType; + XmlSchemaType? schemaTypeObj = _coreReaderImpl.InternalSchemaType as XmlSchemaType; if (schemaTypeObj != null && schemaTypeObj.QualifiedName.Namespace == XmlReservedNs.NsXs) { return schemaTypeObj.Datatype; } + return _coreReaderImpl.InternalSchemaType; } else @@ -932,7 +943,7 @@ namespace System.Xml } // Returns typed value of the current node (based on the type specified by schema) - public object ReadTypedValue() + public object? ReadTypedValue() { if (_validationType == ValidationType.None) { @@ -948,7 +959,8 @@ namespace System.Xml { return null; } - XmlSchemaDatatype dtype = (SchemaType is XmlSchemaDatatype) ? (XmlSchemaDatatype)SchemaType : ((XmlSchemaType)SchemaType).Datatype; + + XmlSchemaDatatype? dtype = (SchemaType is XmlSchemaDatatype) ? (XmlSchemaDatatype)SchemaType : ((XmlSchemaType)SchemaType).Datatype; if (dtype != null) { if (!_outerReader.IsEmptyElement) @@ -959,6 +971,7 @@ namespace System.Xml { throw new InvalidOperationException(SR.Xml_InvalidOperation); } + XmlNodeType type = _outerReader.NodeType; if (type != XmlNodeType.CDATA && type != XmlNodeType.Text && type != XmlNodeType.Whitespace && type != XmlNodeType.SignificantWhitespace && @@ -967,6 +980,7 @@ namespace System.Xml break; } } + if (_outerReader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _outerReader.NodeType.ToString()); @@ -1016,7 +1030,7 @@ namespace System.Xml private void ValidateDtd() { - IDtdInfo dtdInfo = _coreReaderImpl.DtdInfo; + IDtdInfo? dtdInfo = _coreReaderImpl.DtdInfo; if (dtdInfo != null) { switch (_validationType) @@ -1043,26 +1057,28 @@ namespace System.Xml } // SxS: This method resolves an Uri but does not expose it to caller. It's OK to suppress the SxS warning. + [MemberNotNull(nameof(_validator))] private void SetupValidation(ValidationType valType) { - _validator = BaseValidator.CreateInstance(valType, this, _schemaCollection, _eventHandling, _processIdentityConstraints); + _validator = BaseValidator.CreateInstance(valType, this, _schemaCollection, _eventHandling, _processIdentityConstraints)!; - XmlResolver resolver = GetResolver(); + XmlResolver? resolver = GetResolver(); _validator.XmlResolver = resolver; - if (_outerReader.BaseURI.Length > 0) + if (_outerReader.BaseURI!.Length > 0) { _validator.BaseUri = (resolver == null) ? new Uri(_outerReader.BaseURI, UriKind.RelativeOrAbsolute) : resolver.ResolveUri(null, _outerReader.BaseURI); } + _coreReaderImpl.ValidationEventHandling = (_validationType == ValidationType.None) ? null : _eventHandling; } - private static XmlResolver s_tempResolver; + private static XmlResolver? s_tempResolver; // This is needed because we can't have the setter for XmlResolver public and with internal getter. - private XmlResolver GetResolver() + private XmlResolver? GetResolver() { - XmlResolver tempResolver = _coreReaderImpl.GetResolver(); + XmlResolver? tempResolver = _coreReaderImpl.GetResolver(); if (tempResolver == null && !_coreReaderImpl.IsResolverSet) { @@ -1117,7 +1133,7 @@ namespace System.Xml } } - internal override XmlNamespaceManager NamespaceManager + internal override XmlNamespaceManager? NamespaceManager { get { @@ -1133,7 +1149,7 @@ namespace System.Xml } } - internal object SchemaTypeObject + internal object? SchemaTypeObject { set { @@ -1141,7 +1157,7 @@ namespace System.Xml } } - internal object TypedValueObject + internal object? TypedValueObject { get { @@ -1158,24 +1174,25 @@ namespace System.Xml return _coreReaderImpl.AddDefaultAttributeNonDtd(attdef); } - internal override IDtdInfo DtdInfo + internal override IDtdInfo? DtdInfo { get { return _coreReaderImpl.DtdInfo; } } internal void ValidateDefaultAttributeOnUse(IDtdDefaultAttributeInfo defaultAttribute, XmlTextReaderImpl coreReader) { - SchemaAttDef attdef = defaultAttribute as SchemaAttDef; + SchemaAttDef? attdef = defaultAttribute as SchemaAttDef; if (attdef == null) { return; } - SchemaInfo schemaInfo = coreReader.DtdInfo as SchemaInfo; + SchemaInfo? schemaInfo = coreReader.DtdInfo as SchemaInfo; if (schemaInfo == null) { return; } + DtdValidator.CheckDefaultValue(attdef, schemaInfo, _eventHandling, coreReader.BaseURI); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs index 7f23a09..3b91761 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.IO; using System.Text; @@ -63,7 +64,7 @@ namespace System.Xml goto case ParsingFunction.Read; case ParsingFunction.InReadBinaryContent: _parsingFunction = ParsingFunction.Read; - await _readBinaryHelper.FinishAsync().ConfigureAwait(false); + await _readBinaryHelper!.FinishAsync().ConfigureAwait(false); goto case ParsingFunction.Read; default: Debug.Fail($"Unexpected parsing function {_parsingFunction}"); @@ -88,7 +89,7 @@ namespace System.Xml _parsingFunction = ParsingFunction.Read; // call to the helper - int readCount = await _readBinaryHelper.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false); + int readCount = await _readBinaryHelper!.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; @@ -112,7 +113,7 @@ namespace System.Xml _parsingFunction = ParsingFunction.Read; // call to the helper - int readCount = await _readBinaryHelper.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); + int readCount = await _readBinaryHelper!.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; @@ -136,7 +137,7 @@ namespace System.Xml _parsingFunction = ParsingFunction.Read; // call to the helper - int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); + int readCount = await _readBinaryHelper!.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; @@ -160,7 +161,7 @@ namespace System.Xml _parsingFunction = ParsingFunction.Read; // call to the helper - int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); + int readCount = await _readBinaryHelper!.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs index 1487069..738ff3c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs @@ -1343,7 +1343,7 @@ namespace System.Xml } } - public override string XmlLang + public override string? XmlLang { get { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs index c5ca77b..75248f3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs @@ -770,7 +770,7 @@ namespace System.Xml } } - public override async Task WriteCDataAsync(string text) + public override async Task WriteCDataAsync(string? text) { try { @@ -778,6 +778,7 @@ namespace System.Xml { text = string.Empty; } + await AdvanceStateAsync(Token.CData).ConfigureAwait(false); await _writer.WriteCDataAsync(text).ConfigureAwait(false); } @@ -788,7 +789,7 @@ namespace System.Xml } } - public override async Task WriteCommentAsync(string text) + public override async Task WriteCommentAsync(string? text) { try { @@ -796,6 +797,7 @@ namespace System.Xml { text = string.Empty; } + await AdvanceStateAsync(Token.Comment).ConfigureAwait(false); await _writer.WriteCommentAsync(text).ConfigureAwait(false); } @@ -938,7 +940,7 @@ namespace System.Xml } } - public override async Task WriteWhitespaceAsync(string ws) + public override async Task WriteWhitespaceAsync(string? ws) { try { @@ -946,6 +948,7 @@ namespace System.Xml { ws = string.Empty; } + if (!XmlCharType.Instance.IsOnlyWhitespace(ws)) { throw new ArgumentException(SR.Xml_NonWhitespace); @@ -968,7 +971,7 @@ namespace System.Xml } } - public override Task WriteStringAsync(string text) + public override Task WriteStringAsync(string? text) { try { @@ -1460,6 +1463,7 @@ namespace System.Xml await _nsStack[i].WriteDeclAsync(_writer, _rawWriter).ConfigureAwait(false); } } + if (_rawWriter != null) { _rawWriter.StartElementContent(); @@ -1477,6 +1481,7 @@ namespace System.Xml { _rawWriter.StartElementContent(); } + return Task.CompletedTask; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs index de07e0e..09ab727 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs @@ -1,10 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Text; using System.Diagnostics; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -26,12 +28,12 @@ namespace System.Xml { throw new NotImplementedException(); } - string IXmlNamespaceResolver.LookupNamespace(string prefix) + string? IXmlNamespaceResolver.LookupNamespace(string prefix) { return _wfWriter.LookupNamespace(prefix); } - string IXmlNamespaceResolver.LookupPrefix(string namespaceName) + string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _wfWriter.LookupPrefix(namespaceName); } @@ -44,7 +46,7 @@ namespace System.Xml internal string localName; internal string namespaceUri; internal XmlSpace xmlSpace; - internal string xmlLang; + internal string? xmlLang; internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop) { @@ -90,7 +92,7 @@ namespace System.Xml this.prevNsIndex = -1; } - internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter) + internal void WriteDecl(XmlWriter writer, XmlRawWriter? rawWriter) { Debug.Assert(kind == NamespaceKind.NeedToWrite); if (null != rawWriter) @@ -107,6 +109,7 @@ namespace System.Xml { writer.WriteStartAttribute("xmlns", prefix, XmlReservedNs.NsXmlNs); } + writer.WriteString(namespaceUri); writer.WriteEndAttribute(); } @@ -164,8 +167,13 @@ namespace System.Xml internal ItemType type; internal object data; - internal Item() { } + internal Item(ItemType type, object data) + { + Set(type, data); + } + [MemberNotNull(nameof(type))] + [MemberNotNull(nameof(data))] internal void Set(ItemType type, object data) { this.type = type; @@ -188,8 +196,8 @@ namespace System.Xml } private StringBuilder _stringValue = new StringBuilder(); - private string _singleStringValue; // special-case for a single WriteString call - private Item[] _items; + private string? _singleStringValue; // special-case for a single WriteString call + private Item[]? _items; private int _firstItem; private int _lastItem = -1; @@ -344,7 +352,7 @@ namespace System.Xml BufferChunk bufChunk; for (int i = _firstItem; i <= _lastItem; i++) { - Item item = _items[i]; + Item item = _items![i]; switch (item.type) { case ItemType.EntityRef: @@ -408,7 +416,7 @@ namespace System.Xml int i = _firstItem; while (i == _firstItem && i <= _lastItem) { - Item item = _items[i]; + Item item = _items![i]; switch (item.type) { case ItemType.Whitespace: @@ -433,11 +441,13 @@ namespace System.Xml bufChunk.index++; bufChunk.count--; } + if (bufChunk.index == endIndex) { // no characters left -> move the firstItem index to exclude it from the Replay _firstItem++; } + break; } i++; @@ -447,7 +457,7 @@ namespace System.Xml i = _lastItem; while (i == _lastItem && i >= _firstItem) { - Item item = _items[i]; + Item item = _items![i]; switch (item.type) { case ItemType.Whitespace: @@ -470,13 +480,16 @@ namespace System.Xml { bufChunk.count--; } + if (bufChunk.count == 0) { // no characters left -> move the lastItem index to exclude it from the Replay _lastItem--; } + break; } + i--; } } @@ -513,11 +526,16 @@ namespace System.Xml Array.Copy(_items, newItems, newItemIndex); _items = newItems; } + if (_items[newItemIndex] == null) { - _items[newItemIndex] = new Item(); + _items[newItemIndex] = new Item(type, data); + } + else + { + _items[newItemIndex].Set(type, data); } - _items[newItemIndex].Set(type, data); + _lastItem = newItemIndex; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs index ff243e0..9b70772 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Text; using System.Diagnostics; @@ -27,7 +28,7 @@ namespace System.Xml private partial struct Namespace { - internal async Task WriteDeclAsync(XmlWriter writer, XmlRawWriter rawWriter) + internal async Task WriteDeclAsync(XmlWriter writer, XmlRawWriter? rawWriter) { Debug.Assert(kind == NamespaceKind.NeedToWrite); if (null != rawWriter) @@ -63,7 +64,7 @@ namespace System.Xml BufferChunk bufChunk; for (int i = _firstItem; i <= _lastItem; i++) { - Item item = _items[i]; + Item item = _items![i]; switch (item.type) { case ItemType.EntityRef: diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReader.cs index 68d844c..62636bd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReader.cs @@ -61,7 +61,7 @@ namespace System.Xml return reader.GetAttribute(name); } - public override string? GetAttribute(string name, string namespaceURI) + public override string? GetAttribute(string name, string? namespaceURI) { return reader.GetAttribute(name, namespaceURI); } @@ -76,7 +76,7 @@ namespace System.Xml return reader.MoveToAttribute(name); } - public override bool MoveToAttribute(string name, string ns) + public override bool MoveToAttribute(string name, string? ns) { return reader.MoveToAttribute(name, ns); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriter.cs index 217447e..3f334dc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; using System.Collections; @@ -27,10 +28,10 @@ namespace System.Xml // // XmlWriter implementation // - public override XmlWriterSettings Settings { get { return writer.Settings; } } + public override XmlWriterSettings? Settings { get { return writer.Settings; } } public override WriteState WriteState { get { return writer.WriteState; } } public override XmlSpace XmlSpace { get { return writer.XmlSpace; } } - public override string XmlLang { get { return writer.XmlLang; } } + public override string? XmlLang { get { return writer.XmlLang; } } public override void WriteStartDocument() @@ -48,12 +49,12 @@ namespace System.Xml writer.WriteEndDocument(); } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { writer.WriteDocType(name, pubid, sysid, subset); } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { writer.WriteStartElement(prefix, localName, ns); } @@ -68,7 +69,7 @@ namespace System.Xml writer.WriteFullEndElement(); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { writer.WriteStartAttribute(prefix, localName, ns); } @@ -78,17 +79,17 @@ namespace System.Xml writer.WriteEndAttribute(); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { writer.WriteCData(text); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { writer.WriteComment(text); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { writer.WriteProcessingInstruction(name, text); } @@ -103,12 +104,12 @@ namespace System.Xml writer.WriteCharEntity(ch); } - public override void WriteWhitespace(string ws) + public override void WriteWhitespace(string? ws) { writer.WriteWhitespace(ws); } - public override void WriteString(string text) + public override void WriteString(string? text) { writer.WriteString(text); } @@ -148,7 +149,7 @@ namespace System.Xml writer.Flush(); } - public override string LookupPrefix(string ns) + public override string? LookupPrefix(string ns) { return writer.LookupPrefix(ns); } @@ -158,7 +159,7 @@ namespace System.Xml writer.WriteValue(value); } - public override void WriteValue(string value) + public override void WriteValue(string? value) { writer.WriteValue(value); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriterAsync.cs index 53dcf58..46c2d67 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriterAsync.cs @@ -59,12 +59,12 @@ namespace System.Xml return writer.WriteEndAttributeAsync(); } - public override Task WriteCDataAsync(string text) + public override Task WriteCDataAsync(string? text) { return writer.WriteCDataAsync(text); } - public override Task WriteCommentAsync(string text) + public override Task WriteCommentAsync(string? text) { return writer.WriteCommentAsync(text); } @@ -84,12 +84,12 @@ namespace System.Xml return writer.WriteCharEntityAsync(ch); } - public override Task WriteWhitespaceAsync(string ws) + public override Task WriteWhitespaceAsync(string? ws) { return writer.WriteWhitespaceAsync(ws); } - public override Task WriteStringAsync(string text) + public override Task WriteStringAsync(string? text) { return writer.WriteStringAsync(text); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs index 22baf19..b35c292 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs @@ -107,14 +107,14 @@ namespace System.Xml // Writes out a ; block containing the specified text. - public virtual Task WriteCDataAsync(string text) + public virtual Task WriteCDataAsync(string? text) { throw new NotImplementedException(); } // Writes out a comment ; containing the specified text. - public virtual Task WriteCommentAsync(string text) + public virtual Task WriteCommentAsync(string? text) { throw new NotImplementedException(); } @@ -142,14 +142,14 @@ namespace System.Xml // Writes out the given whitespace. - public virtual Task WriteWhitespaceAsync(string ws) + public virtual Task WriteWhitespaceAsync(string? ws) { throw new NotImplementedException(); } // Writes out the specified text content. - public virtual Task WriteStringAsync(string text) + public virtual Task WriteStringAsync(string? text) { throw new NotImplementedException(); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs index f0ff98e..5cde9f0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs @@ -1,11 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Runtime.Versioning; +using System.Diagnostics.CodeAnalysis; #if !HIDE_XSL using System.Xml.Xsl.Runtime; @@ -72,9 +74,9 @@ namespace System.Xml private List _cdataSections = new List(); private bool _doNotEscapeUriAttributes; private bool _mergeCDataSections; - private string _mediaType; - private string _docTypeSystem; - private string _docTypePublic; + private string? _mediaType; + private string? _docTypeSystem; + private string? _docTypePublic; private XmlStandalone _standalone; private bool _autoXmlDecl; @@ -113,6 +115,7 @@ namespace System.Xml { return _encoding; } + [MemberNotNull(nameof(_encoding))] set { CheckReadOnly(nameof(Encoding)); @@ -149,6 +152,7 @@ namespace System.Xml { throw new ArgumentOutOfRangeException(nameof(value)); } + _newLineHandling = value; } } @@ -160,6 +164,7 @@ namespace System.Xml { return _newLineChars; } + [MemberNotNull(nameof(_newLineChars))] set { CheckReadOnly(nameof(NewLineChars)); @@ -168,6 +173,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(value)); } + _newLineChars = value; } } @@ -193,6 +199,7 @@ namespace System.Xml { return _indentChars; } + [MemberNotNull(nameof(_indentChars))] set { CheckReadOnly(nameof(IndentChars)); @@ -201,6 +208,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(value)); } + _indentChars = value; } } @@ -326,7 +334,7 @@ namespace System.Xml // can now be set independently of each other. public XmlWriterSettings Clone() { - XmlWriterSettings clonedSettings = MemberwiseClone() as XmlWriterSettings; + XmlWriterSettings clonedSettings = (MemberwiseClone() as XmlWriterSettings)!; // Deep clone shared settings that are not immutable clonedSettings._cdataSections = new List(_cdataSections); @@ -376,7 +384,7 @@ namespace System.Xml } // Used in Html writer when writing Meta element. Null denotes the default media type. - internal string MediaType + internal string? MediaType { get { @@ -390,7 +398,7 @@ namespace System.Xml } // System Id in doc-type declaration. Null denotes the absence of the system Id. - internal string DocTypeSystem + internal string? DocTypeSystem { get { @@ -404,7 +412,7 @@ namespace System.Xml } // Public Id in doc-type declaration. Null denotes the absence of the public Id. - internal string DocTypePublic + internal string? DocTypePublic { get { @@ -483,7 +491,7 @@ namespace System.Xml newSettings.CloseOutput = true; } - FileStream fs = null; + FileStream? fs = null; try { // open file stream @@ -705,6 +713,9 @@ namespace System.Xml // // Private methods // + [MemberNotNull(nameof(_encoding))] + [MemberNotNull(nameof(_newLineChars))] + [MemberNotNull(nameof(_indentChars))] private void Initialize() { _encoding = Encoding.UTF8; @@ -736,7 +747,7 @@ namespace System.Xml private XmlWriter AddConformanceWrapper(XmlWriter baseWriter) { ConformanceLevel confLevel = ConformanceLevel.Auto; - XmlWriterSettings baseWriterSettings = baseWriter.Settings; + XmlWriterSettings? baseWriterSettings = baseWriter.Settings; bool checkValues = false; bool checkNames = false; bool replaceNewLines = false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs index ade6535..119604e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.IO; using System.Text; using System.Xml.Schema; @@ -8,6 +9,7 @@ using System.Xml.XPath; using System.Diagnostics; using System.Globalization; using System.Collections; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -29,7 +31,7 @@ namespace System.Xml private ValidatingReaderNodeData[] _contentEvents; private ValidatingReaderNodeData[] _attributeEvents; - private ValidatingReaderNodeData _cachedNode; + private ValidatingReaderNodeData? _cachedNode; private CachingReaderState _cacheState; private int _contentIndex; @@ -45,17 +47,17 @@ namespace System.Xml private bool _readAhead; //Lineinfo - private readonly IXmlLineInfo _lineInfo; + private readonly IXmlLineInfo? _lineInfo; //ReadAttributeValue TextNode - private ValidatingReaderNodeData _textNode; + private ValidatingReaderNodeData? _textNode; //Constants private const int InitialAttributeCount = 8; private const int InitialContentCount = 4; //Constructor - internal XsdCachingReader(XmlReader reader, IXmlLineInfo lineInfo, CachingEventHandler handlerMethod) + internal XsdCachingReader(XmlReader reader, IXmlLineInfo? lineInfo, CachingEventHandler handlerMethod) { _coreReader = reader; _lineInfo = lineInfo; @@ -65,6 +67,7 @@ namespace System.Xml Init(); } + [MemberNotNull(nameof(_coreReaderNameTable))] private void Init() { _coreReaderNameTable = _coreReader.NameTable; @@ -92,7 +95,7 @@ namespace System.Xml } // Settings - public override XmlReaderSettings Settings + public override XmlReaderSettings? Settings { get { @@ -107,7 +110,7 @@ namespace System.Xml { get { - return _cachedNode.NodeType; + return _cachedNode!.NodeType; } } @@ -116,7 +119,7 @@ namespace System.Xml { get { - return _cachedNode.GetAtomizedNameWPrefix(_coreReaderNameTable); + return _cachedNode!.GetAtomizedNameWPrefix(_coreReaderNameTable); } } @@ -125,7 +128,7 @@ namespace System.Xml { get { - return _cachedNode.LocalName; + return _cachedNode!.LocalName; } } @@ -134,7 +137,7 @@ namespace System.Xml { get { - return _cachedNode.Namespace; + return _cachedNode!.Namespace; } } @@ -143,7 +146,7 @@ namespace System.Xml { get { - return _cachedNode.Prefix; + return _cachedNode!.Prefix; } } @@ -152,7 +155,7 @@ namespace System.Xml { get { - return XmlReader.HasValueInternal(_cachedNode.NodeType); + return XmlReader.HasValueInternal(_cachedNode!.NodeType); } } @@ -161,7 +164,7 @@ namespace System.Xml { get { - return _returnOriginalStringValues ? _cachedNode.OriginalStringValue : _cachedNode.RawValue; + return _returnOriginalStringValues ? _cachedNode!.OriginalStringValue! : _cachedNode!.RawValue; } } @@ -170,12 +173,12 @@ namespace System.Xml { get { - return _cachedNode.Depth; + return _cachedNode!.Depth; } } // Gets the base URI of the current node. - public override string BaseURI + public override string? BaseURI { get { @@ -241,7 +244,7 @@ namespace System.Xml } // Gets the value of the attribute with the specified Name. - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { int i; if (!name.Contains(':')) @@ -252,23 +255,25 @@ namespace System.Xml { i = GetAttributeIndexWithPrefix(name); } + return (i >= 0) ? _attributeEvents[i].RawValue : null; } // Gets the value of the attribute with the specified LocalName and NamespaceURI. - public override string GetAttribute(string name, string namespaceURI) + public override string? GetAttribute(string name, string? namespaceURI) { namespaceURI = (namespaceURI == null) ? string.Empty : _coreReaderNameTable.Get(namespaceURI); - name = _coreReaderNameTable.Get(name); + string? atomizedName = _coreReaderNameTable.Get(name); ValidatingReaderNodeData attribute; for (int i = 0; i < _attributeCount; i++) { attribute = _attributeEvents[i]; - if (Ref.Equal(attribute.LocalName, name) && Ref.Equal(attribute.Namespace, namespaceURI)) + if (Ref.Equal(attribute.LocalName, atomizedName) && Ref.Equal(attribute.Namespace, namespaceURI)) { return attribute.RawValue; } } + return null; } @@ -279,6 +284,7 @@ namespace System.Xml { throw new ArgumentOutOfRangeException(nameof(i)); } + return _attributeEvents[i].RawValue; } @@ -292,7 +298,7 @@ namespace System.Xml } // Gets the value of the attribute with the specified LocalName and NamespaceURI. - public override string this[string name, string namespaceURI] + public override string? this[string name, string? namespaceURI] { get { @@ -326,15 +332,15 @@ namespace System.Xml } // Moves to the attribute with the specified LocalName and NamespaceURI - public override bool MoveToAttribute(string name, string ns) + public override bool MoveToAttribute(string name, string? ns) { ns = (ns == null) ? string.Empty : _coreReaderNameTable.Get(ns); - name = _coreReaderNameTable.Get(name); + string? atomizedName = _coreReaderNameTable.Get(name); ValidatingReaderNodeData attribute; for (int i = 0; i < _attributeCount; i++) { attribute = _attributeEvents[i]; - if (Ref.Equal(attribute.LocalName, name) && + if (Ref.Equal(attribute.LocalName, atomizedName) && Ref.Equal(attribute.Namespace, ns)) { _currentAttrIndex = i; @@ -342,6 +348,7 @@ namespace System.Xml return true; } } + return false; } @@ -382,10 +389,11 @@ namespace System.Xml // Moves to the element that contains the current attribute node. public override bool MoveToElement() { - if (_cacheState != CachingReaderState.Replay || _cachedNode.NodeType != XmlNodeType.Attribute) + if (_cacheState != CachingReaderState.Replay || _cachedNode!.NodeType != XmlNodeType.Attribute) { return false; } + _currentContentIndex = 0; _currentAttrIndex = -1; Read(); @@ -402,7 +410,7 @@ namespace System.Xml goto case CachingReaderState.Record; case CachingReaderState.Record: - ValidatingReaderNodeData recordedNode = null; + ValidatingReaderNodeData? recordedNode = null; if (_coreReader.Read()) { switch (_coreReader.NodeType) @@ -466,7 +474,7 @@ namespace System.Xml } } - internal ValidatingReaderNodeData RecordTextNode(string textValue, string originalStringValue, int depth, int lineNo, int linePos) + internal ValidatingReaderNodeData RecordTextNode(string textValue, string? originalStringValue, int depth, int lineNo, int linePos) { ValidatingReaderNodeData textNode = AddContent(XmlNodeType.Text); textNode.SetItemData(textValue, originalStringValue); @@ -475,7 +483,7 @@ namespace System.Xml return textNode; } - internal void SwitchTextNodeAndEndElement(string textValue, string originalStringValue) + internal void SwitchTextNodeAndEndElement(string textValue, string? originalStringValue) { Debug.Assert(_coreReader.NodeType == XmlNodeType.EndElement || (_coreReader.NodeType == XmlNodeType.Element && _coreReader.IsEmptyElement)); @@ -536,7 +544,7 @@ namespace System.Xml public override void Skip() { //Skip on caching reader should move to the end of the subtree, past all cached events - switch (_cachedNode.NodeType) + switch (_cachedNode!.NodeType) { case XmlNodeType.Element: if (_coreReader.NodeType != XmlNodeType.EndElement && !_readAhead) @@ -571,7 +579,7 @@ namespace System.Xml } // Resolves a namespace prefix in the current element's scope. - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { return _coreReader.LookupNamespace(prefix); } @@ -586,10 +594,11 @@ namespace System.Xml public override bool ReadAttributeValue() { Debug.Assert(_cacheState == CachingReaderState.Replay); - if (_cachedNode.NodeType != XmlNodeType.Attribute) + if (_cachedNode!.NodeType != XmlNodeType.Attribute) { return false; } + _cachedNode = CreateDummyTextNode(_cachedNode.RawValue, _cachedNode.Depth + 1); return true; } @@ -607,7 +616,7 @@ namespace System.Xml { get { - return _cachedNode.LineNumber; + return _cachedNode!.LineNumber; } } @@ -615,7 +624,7 @@ namespace System.Xml { get { - return _cachedNode.LinePosition; + return _cachedNode!.LinePosition; } } @@ -633,7 +642,7 @@ namespace System.Xml return _coreReader; } - internal IXmlLineInfo GetLineInfo() + internal IXmlLineInfo? GetLineInfo() { return _lineInfo; } @@ -716,16 +725,17 @@ namespace System.Xml private int GetAttributeIndexWithoutPrefix(string name) { - name = _coreReaderNameTable.Get(name); - if (name == null) + string? atomizedName = _coreReaderNameTable.Get(name); + if (atomizedName == null) { return -1; } + ValidatingReaderNodeData attribute; for (int i = 0; i < _attributeCount; i++) { attribute = _attributeEvents[i]; - if (Ref.Equal(attribute.LocalName, name) && attribute.Prefix.Length == 0) + if (Ref.Equal(attribute.LocalName, atomizedName) && attribute.Prefix.Length == 0) { return i; } @@ -735,8 +745,8 @@ namespace System.Xml private int GetAttributeIndexWithPrefix(string name) { - name = _coreReaderNameTable.Get(name); - if (name == null) + string? atomizedName = _coreReaderNameTable.Get(name); + if (atomizedName == null) { return -1; } @@ -744,11 +754,12 @@ namespace System.Xml for (int i = 0; i < _attributeCount; i++) { attribute = _attributeEvents[i]; - if (Ref.Equal(attribute.GetAtomizedNameWPrefix(_coreReaderNameTable), name)) + if (Ref.Equal(attribute.GetAtomizedNameWPrefix(_coreReaderNameTable), atomizedName)) { return i; } } + return -1; } @@ -758,6 +769,7 @@ namespace System.Xml { _textNode = new ValidatingReaderNodeData(XmlNodeType.Text); } + _textNode.Depth = depth; _textNode.RawValue = attributeValue; return _textNode; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReaderAsync.cs index 914e5ff..9abcb81 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReaderAsync.cs @@ -21,11 +21,11 @@ namespace System.Xml { if (_returnOriginalStringValues) { - return Task.FromResult(_cachedNode.OriginalStringValue); + return Task.FromResult(_cachedNode!.OriginalStringValue!); } else { - return Task.FromResult(_cachedNode.RawValue); + return Task.FromResult(_cachedNode!.RawValue); } } @@ -107,7 +107,7 @@ namespace System.Xml public override async Task SkipAsync() { //Skip on caching reader should move to the end of the subtree, past all cached events - switch (_cachedNode.NodeType) + switch (_cachedNode!.NodeType) { case XmlNodeType.Element: if (_coreReader.NodeType != XmlNodeType.EndElement && !_readAhead) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs index a6ce8d9..cc0b405 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs @@ -1135,7 +1135,7 @@ namespace System.Xml } // Gets the value of the attribute with the specified LocalName and NamespaceURI. - public override string? GetAttribute(string name, string namespaceURI) + public override string? GetAttribute(string name, string? namespaceURI) { string? attValue = _coreReader.GetAttribute(name, namespaceURI); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs index deb041c..a7c1c2d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Text; using System.Collections; @@ -18,31 +19,31 @@ namespace System.Xml { internal sealed class DocumentSchemaValidator : IXmlNamespaceResolver { - private XmlSchemaValidator _validator; + private XmlSchemaValidator? _validator; private readonly XmlSchemaSet _schemas; private readonly XmlNamespaceManager _nsManager; private readonly XmlNameTable _nameTable; //Attributes - private ArrayList _defaultAttributes; + private ArrayList? _defaultAttributes; private readonly XmlValueGetter _nodeValueGetter; - private XmlSchemaInfo _attributeSchemaInfo; + private XmlSchemaInfo? _attributeSchemaInfo; //Element PSVI - private XmlSchemaInfo _schemaInfo; + private XmlSchemaInfo? _schemaInfo; //Event Handler - private readonly ValidationEventHandler _eventHandler; + private readonly ValidationEventHandler? _eventHandler; private readonly ValidationEventHandler _internalEventHandler; //Store nodes - private XmlNode _startNode; - private XmlNode _currentNode; + private XmlNode? _startNode; + private XmlNode? _currentNode; private readonly XmlDocument _document; //List of nodes for partial validation tree walk - private XmlNode[] _nodeSequenceToValidate; + private XmlNode?[]? _nodeSequenceToValidate; private bool _isPartialTreeValid; private bool _psviAugmentation; @@ -54,7 +55,7 @@ namespace System.Xml private readonly string _xsiType; private readonly string _xsiNil; - public DocumentSchemaValidator(XmlDocument ownerDocument, XmlSchemaSet schemas, ValidationEventHandler eventHandler) + public DocumentSchemaValidator(XmlDocument ownerDocument, XmlSchemaSet schemas, ValidationEventHandler? eventHandler) { _schemas = schemas; _eventHandler = eventHandler; @@ -84,7 +85,7 @@ namespace System.Xml public bool Validate(XmlNode nodeToValidate) { - XmlSchemaObject partialValidationType = null; + XmlSchemaObject? partialValidationType = null; XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes; Debug.Assert(nodeToValidate.SchemaInfo != null); @@ -100,7 +101,7 @@ namespace System.Xml case XmlNodeType.Element: //Validate children of this element IXmlSchemaInfo schemaInfo = nodeToValidate.SchemaInfo; - XmlSchemaElement schemaElement = schemaInfo.SchemaElement; + XmlSchemaElement? schemaElement = schemaInfo.SchemaElement; if (schemaElement != null) { if (!schemaElement.RefName.IsEmpty) @@ -120,14 +121,14 @@ namespace System.Xml if (partialValidationType == null) { //Validated against xs:any with pc= lax or skip or undeclared / not validated element - if (nodeToValidate.ParentNode.NodeType == XmlNodeType.Document) + 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); + partialValidationType = FindSchemaInfo((nodeToValidate as XmlElement)!); if (partialValidationType == null) { throw new XmlSchemaValidationException(SR.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate); @@ -142,7 +143,7 @@ namespace System.Xml partialValidationType = nodeToValidate.SchemaInfo.SchemaAttribute; if (partialValidationType == null) { //Validated against xs:anyAttribute with pc = lax or skip / undeclared attribute - partialValidationType = FindSchemaInfo(nodeToValidate as XmlAttribute); + partialValidationType = FindSchemaInfo((nodeToValidate as XmlAttribute)!); if (partialValidationType == null) { throw new XmlSchemaValidationException(SR.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate); @@ -164,7 +165,7 @@ namespace System.Xml _attributeSchemaInfo = new XmlSchemaInfo(); } ValidateNode(nodeToValidate); - _validator.EndValidation(); + _validator!.EndValidation(); return _isValid; } @@ -173,7 +174,7 @@ namespace System.Xml IDictionary dictionary = _nsManager.GetNamespacesInScope(scope); if (scope != XmlNamespaceScope.Local) { - XmlNode node = _startNode; + XmlNode? node = _startNode; while (node != null) { switch (node.NodeType) @@ -221,23 +222,25 @@ namespace System.Xml return dictionary; } - public string LookupNamespace(string prefix) + public string? LookupNamespace(string prefix) { - string namespaceName = _nsManager.LookupNamespace(prefix); + string? namespaceName = _nsManager.LookupNamespace(prefix); if (namespaceName == null) { - namespaceName = _startNode.GetNamespaceOfPrefixStrict(prefix); + namespaceName = _startNode!.GetNamespaceOfPrefixStrict(prefix); } + return namespaceName; } - public string LookupPrefix(string namespaceName) + public string? LookupPrefix(string namespaceName) { - string prefix = _nsManager.LookupPrefix(namespaceName); + string? prefix = _nsManager.LookupPrefix(namespaceName); if (prefix == null) { - prefix = _startNode.GetPrefixOfNamespaceStrict(namespaceName); + prefix = _startNode!.GetPrefixOfNamespaceStrict(namespaceName); } + return prefix; } @@ -245,15 +248,16 @@ namespace System.Xml { get { - if ((object)_startNode == (object)_document) + if ((object?)_startNode == (object?)_document) { return _nsManager; } + return this; } } - private void CreateValidator(XmlSchemaObject partialValidationType, XmlSchemaValidationFlags validationFlags) + private void CreateValidator(XmlSchemaObject? partialValidationType, XmlSchemaValidationFlags validationFlags) { _validator = new XmlSchemaValidator(_nameTable, _schemas, NamespaceResolver, validationFlags); _validator.SourceUri = XmlConvert.ToUri(_document.BaseURI); @@ -277,20 +281,22 @@ namespace System.Xml switch (_currentNode.NodeType) { case XmlNodeType.Document: - XmlElement docElem = ((XmlDocument)node).DocumentElement; + XmlElement? docElem = ((XmlDocument)node).DocumentElement; if (docElem == null) { throw new InvalidOperationException(SR.Format(SR.Xml_InvalidXmlDocument, SR.Xdom_NoRootEle)); } + ValidateNode(docElem); break; case XmlNodeType.DocumentFragment: case XmlNodeType.EntityReference: - for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = node.FirstChild; child != null; child = child.NextSibling) { ValidateNode(child); } + break; case XmlNodeType.Element: @@ -298,8 +304,8 @@ namespace System.Xml break; case XmlNodeType.Attribute: //Top-level attribute - XmlAttribute attr = _currentNode as XmlAttribute; - _validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo); + 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); @@ -307,16 +313,16 @@ namespace System.Xml break; case XmlNodeType.Text: - _validator.ValidateText(_nodeValueGetter); + _validator!.ValidateText(_nodeValueGetter); break; case XmlNodeType.CDATA: - _validator.ValidateText(_nodeValueGetter); + _validator!.ValidateText(_nodeValueGetter); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: - _validator.ValidateWhitespace(_nodeValueGetter); + _validator!.ValidateWhitespace(_nodeValueGetter); break; case XmlNodeType.Comment: @@ -331,15 +337,15 @@ namespace System.Xml private void ValidateElement() { _nsManager.PushScope(); - XmlElement elementNode = _currentNode as XmlElement; + XmlElement? elementNode = _currentNode as XmlElement; Debug.Assert(elementNode != null); XmlAttributeCollection attributes = elementNode.Attributes; - XmlAttribute attr = null; + XmlAttribute? attr = null; //Find Xsi attributes that need to be processed before validating the element - string xsiNil = null; - string xsiType = null; + string? xsiNil = null; + string? xsiType = null; for (int i = 0; i < attributes.Count; i++) { @@ -365,15 +371,17 @@ namespace System.Xml _nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value); } } - _validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo, xsiType, xsiNil, null, null); + + _validator!.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo, xsiType, xsiNil, null, null); ValidateAttributes(elementNode); - _validator.ValidateEndOfAttributes(_schemaInfo); + _validator!.ValidateEndOfAttributes(_schemaInfo); //If element has children, drill down - for (XmlNode child = elementNode.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = elementNode.FirstChild; child != null; child = child.NextSibling) { ValidateNode(child); } + //Validate end of element _currentNode = elementNode; //Reset current Node for validation call back _validator.ValidateEndElement(_schemaInfo); @@ -381,9 +389,9 @@ namespace System.Xml if (_psviAugmentation) { elementNode.XmlName = _document.AddXmlName(elementNode.Prefix, elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo); - if (_schemaInfo.IsDefault) + if (_schemaInfo!.IsDefault) { //the element has a default value - XmlText textNode = _document.CreateTextNode(_schemaInfo.SchemaElement.ElementDecl.DefaultValueRaw); + XmlText textNode = _document.CreateTextNode(_schemaInfo.SchemaElement!.ElementDecl!.DefaultValueRaw); elementNode.AppendChild(textNode); } } @@ -394,7 +402,7 @@ namespace System.Xml private void ValidateAttributes(XmlElement elementNode) { XmlAttributeCollection attributes = elementNode.Attributes; - XmlAttribute attr = null; + XmlAttribute? attr = null; for (int i = 0; i < attributes.Count; i++) { @@ -404,7 +412,7 @@ namespace System.Xml { //Do not validate namespace decls continue; } - _validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo); + _validator!.ValidateAttribute(attr.LocalName, attr.NamespaceURI, _nodeValueGetter, _attributeSchemaInfo); if (_psviAugmentation) { attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo); @@ -422,21 +430,20 @@ namespace System.Xml { _defaultAttributes.Clear(); } - _validator.GetUnspecifiedDefaultAttributes(_defaultAttributes); - XmlSchemaAttribute schemaAttribute = null; + _validator!.GetUnspecifiedDefaultAttributes(_defaultAttributes); XmlQualifiedName attrQName; attr = null; for (int i = 0; i < _defaultAttributes.Count; i++) { - schemaAttribute = _defaultAttributes[i] as XmlSchemaAttribute; + XmlSchemaAttribute schemaAttribute = (_defaultAttributes[i] as XmlSchemaAttribute)!; attrQName = schemaAttribute.QualifiedName; Debug.Assert(schemaAttribute != null); attr = _document.CreateDefaultAttribute(GetDefaultPrefix(attrQName.Namespace), attrQName.Name, attrQName.Namespace); SetDefaultAttributeSchemaInfo(schemaAttribute); attr.XmlName = _document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, _attributeSchemaInfo); - attr.AppendChild(_document.CreateTextNode(schemaAttribute.AttDef.DefaultValueRaw)); + attr.AppendChild(_document.CreateTextNode(schemaAttribute.AttDef!.DefaultValueRaw)); attributes.Append(attr); - XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute; + XmlUnspecifiedAttribute? defAttr = attr as XmlUnspecifiedAttribute; if (defAttr != null) { defAttr.SetSpecified(false); @@ -455,20 +462,20 @@ namespace System.Xml _attributeSchemaInfo.SchemaAttribute = schemaAttribute; //Get memberType for default attribute - SchemaAttDef attributeDef = schemaAttribute.AttDef; + SchemaAttDef attributeDef = schemaAttribute.AttDef!; if (attributeDef.Datatype.Variety == XmlSchemaDatatypeVariety.Union) { - XsdSimpleValue simpleValue = attributeDef.DefaultValueTyped as XsdSimpleValue; + XsdSimpleValue? simpleValue = attributeDef.DefaultValueTyped as XsdSimpleValue; Debug.Assert(simpleValue != null); _attributeSchemaInfo.MemberType = simpleValue.XmlType; } _attributeSchemaInfo.Validity = XmlSchemaValidity.Valid; } - private string GetDefaultPrefix(string attributeNS) + private string? GetDefaultPrefix(string attributeNS) { IDictionary namespaceDecls = NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.All); - string defaultPrefix = null; + string? defaultPrefix = null; string defaultNS; attributeNS = _nameTable.Add(attributeNS); //atomize ns @@ -484,43 +491,44 @@ namespace System.Xml } } } + return defaultPrefix; } - private object GetNodeValue() + private object? GetNodeValue() { - return _currentNode.Value; + return _currentNode!.Value; } //Code for finding type during partial validation - private XmlSchemaObject FindSchemaInfo(XmlElement elementToValidate) + private XmlSchemaObject? FindSchemaInfo(XmlElement elementToValidate) { _isPartialTreeValid = true; - Debug.Assert(elementToValidate.ParentNode.NodeType != XmlNodeType.Document); //Handle if it is the documentElement separately + Debug.Assert(elementToValidate.ParentNode!.NodeType != XmlNodeType.Document); //Handle if it is the documentElement separately //Create nodelist to navigate down again XmlNode currentNode = elementToValidate; - IXmlSchemaInfo parentSchemaInfo = null; + IXmlSchemaInfo? parentSchemaInfo = null; int nodeIndex = 0; //Check common case of parent node first - XmlNode parentNode = currentNode.ParentNode; + XmlNode? parentNode = currentNode.ParentNode; do { - parentSchemaInfo = parentNode.SchemaInfo; + parentSchemaInfo = parentNode!.SchemaInfo; if (parentSchemaInfo.SchemaElement != null || parentSchemaInfo.SchemaType != null) { break; //Found ancestor with schemaInfo } CheckNodeSequenceCapacity(nodeIndex); - _nodeSequenceToValidate[nodeIndex++] = parentNode; + _nodeSequenceToValidate![nodeIndex++] = parentNode; parentNode = parentNode.ParentNode; } while (parentNode != null); if (parentNode == null) { //Did not find any type info all the way to the root, currentNode is Document || DocumentFragment nodeIndex = nodeIndex - 1; //Subtract the one for document and set the node to null - _nodeSequenceToValidate[nodeIndex] = null; + _nodeSequenceToValidate![nodeIndex] = null; return GetTypeFromAncestors(elementToValidate, null, nodeIndex); } else @@ -528,8 +536,8 @@ namespace System.Xml //Start validating down from the parent or ancestor that has schema info and shallow validate all previous siblings //to correctly ascertain particle for current node CheckNodeSequenceCapacity(nodeIndex); - _nodeSequenceToValidate[nodeIndex++] = parentNode; - XmlSchemaObject ancestorSchemaObject = parentSchemaInfo.SchemaElement; + _nodeSequenceToValidate![nodeIndex++] = parentNode; + XmlSchemaObject? ancestorSchemaObject = parentSchemaInfo.SchemaElement; if (ancestorSchemaObject == null) { ancestorSchemaObject = parentSchemaInfo.SchemaType; @@ -563,23 +571,24 @@ namespace System.Xml } } - private XmlSchemaAttribute FindSchemaInfo(XmlAttribute attributeToValidate) + private XmlSchemaAttribute? FindSchemaInfo(XmlAttribute attributeToValidate) { - XmlElement parentElement = attributeToValidate.OwnerElement; - XmlSchemaObject schemaObject = FindSchemaInfo(parentElement); - XmlSchemaComplexType elementSchemaType = GetComplexType(schemaObject); + XmlElement parentElement = attributeToValidate.OwnerElement!; + XmlSchemaObject? schemaObject = FindSchemaInfo(parentElement); + XmlSchemaComplexType? elementSchemaType = GetComplexType(schemaObject); if (elementSchemaType == null) { return null; } + XmlQualifiedName attName = new XmlQualifiedName(attributeToValidate.LocalName, attributeToValidate.NamespaceURI); - XmlSchemaAttribute schemaAttribute = elementSchemaType.AttributeUses[attName] as XmlSchemaAttribute; + XmlSchemaAttribute? schemaAttribute = elementSchemaType.AttributeUses[attName] as XmlSchemaAttribute; if (schemaAttribute == null) { - XmlSchemaAnyAttribute anyAttribute = elementSchemaType.AttributeWildcard; + XmlSchemaAnyAttribute? anyAttribute = elementSchemaType.AttributeWildcard; if (anyAttribute != null) { - if (anyAttribute.NamespaceList.Allows(attName)) + if (anyAttribute.NamespaceList!.Allows(attName)) { //Match wildcard against global attribute schemaAttribute = _schemas.GlobalAttributes[attName] as XmlSchemaAttribute; } @@ -588,7 +597,7 @@ namespace System.Xml return schemaAttribute; } - private XmlSchemaObject GetTypeFromAncestors(XmlElement elementToValidate, XmlSchemaObject ancestorType, int ancestorsCount) + private XmlSchemaObject? GetTypeFromAncestors(XmlElement elementToValidate, XmlSchemaObject? ancestorType, int ancestorsCount) { //schemaInfo is currentNode's schemaInfo _validator = CreateTypeFinderValidator(ancestorType); @@ -600,8 +609,8 @@ namespace System.Xml bool ancestorHasWildCard = AncestorTypeHasWildcard(ancestorType); for (int i = startIndex; i >= 0; i--) { - XmlNode node = _nodeSequenceToValidate[i]; - XmlElement currentElement = node as XmlElement; + XmlNode node = _nodeSequenceToValidate![i]!; + XmlElement currentElement = (node as XmlElement)!; ValidateSingleElement(currentElement, false, _schemaInfo); if (!ancestorHasWildCard) { //store type if ancestor does not have wildcard in its content model @@ -613,7 +622,7 @@ namespace System.Xml _validator.ValidateEndOfAttributes(null); if (i > 0) { - ValidateChildrenTillNextAncestor(node, _nodeSequenceToValidate[i - 1]); + ValidateChildrenTillNextAncestor(node, _nodeSequenceToValidate[i - 1]!); } else { //i == 0 @@ -621,11 +630,11 @@ namespace System.Xml } } - Debug.Assert(_nodeSequenceToValidate[0] == elementToValidate.ParentNode); + Debug.Assert(_nodeSequenceToValidate![0] == elementToValidate.ParentNode); //validate element whose type is needed, ValidateSingleElement(elementToValidate, false, _schemaInfo); - XmlSchemaObject schemaInfoFound = null; + XmlSchemaObject? schemaInfoFound = null; if (_schemaInfo.SchemaElement != null) { schemaInfoFound = _schemaInfo.SchemaElement; @@ -651,24 +660,26 @@ namespace System.Xml return schemaInfoFound; } - private bool AncestorTypeHasWildcard(XmlSchemaObject ancestorType) + private bool AncestorTypeHasWildcard(XmlSchemaObject? ancestorType) { - XmlSchemaComplexType ancestorSchemaType = GetComplexType(ancestorType); + XmlSchemaComplexType? ancestorSchemaType = GetComplexType(ancestorType); if (ancestorType != null) { - return ancestorSchemaType.HasWildCard; + return ancestorSchemaType!.HasWildCard; } + return false; } - private XmlSchemaComplexType GetComplexType(XmlSchemaObject schemaObject) + private XmlSchemaComplexType? GetComplexType(XmlSchemaObject? schemaObject) { if (schemaObject == null) { return null; } - XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement; - XmlSchemaComplexType complexType = null; + + XmlSchemaElement? schemaElement = schemaObject as XmlSchemaElement; + XmlSchemaComplexType? complexType = null; if (schemaElement != null) { complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType; @@ -677,20 +688,21 @@ namespace System.Xml { complexType = schemaObject as XmlSchemaComplexType; } + return complexType; } - private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSchemaInfo newSchemaInfo) + private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSchemaInfo? newSchemaInfo) { _nsManager.PushScope(); Debug.Assert(elementNode != null); XmlAttributeCollection attributes = elementNode.Attributes; - XmlAttribute attr = null; + XmlAttribute? attr = null; //Find Xsi attributes that need to be processed before validating the element - string xsiNil = null; - string xsiType = null; + string? xsiNil = null; + string? xsiType = null; for (int i = 0; i < attributes.Count; i++) { @@ -716,19 +728,20 @@ namespace System.Xml _nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value); } } - _validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, newSchemaInfo, xsiType, xsiNil, null, null); + + _validator!.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, newSchemaInfo, xsiType, xsiNil, null, null); //Validate end of element if (skipToEnd) { - _validator.ValidateEndOfAttributes(newSchemaInfo); - _validator.SkipToEndElement(newSchemaInfo); + _validator!.ValidateEndOfAttributes(newSchemaInfo); + _validator!.SkipToEndElement(newSchemaInfo); _nsManager.PopScope(); //Pop current namespace scope } } private void ValidateChildrenTillNextAncestor(XmlNode parentNode, XmlNode childToStopAt) { - XmlNode child; + XmlNode? child; for (child = parentNode.FirstChild; child != null; child = child.NextSibling) { @@ -736,6 +749,7 @@ namespace System.Xml { break; } + switch (child.NodeType) { case XmlNodeType.EntityReference: @@ -743,17 +757,17 @@ namespace System.Xml break; case XmlNodeType.Element: //Flat validation, do not drill down into children - ValidateSingleElement(child as XmlElement, true, null); + ValidateSingleElement((child as XmlElement)!, true, null); break; case XmlNodeType.Text: case XmlNodeType.CDATA: - _validator.ValidateText(child.Value); + _validator!.ValidateText(child.Value!); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: - _validator.ValidateWhitespace(child.Value); + _validator!.ValidateWhitespace(child.Value!); break; case XmlNodeType.Comment: @@ -761,13 +775,14 @@ namespace System.Xml break; default: - throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, _currentNode.NodeType)); + throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, _currentNode!.NodeType)); } } + Debug.Assert(child == childToStopAt); } - private XmlSchemaValidator CreateTypeFinderValidator(XmlSchemaObject partialValidationType) + private XmlSchemaValidator CreateTypeFinderValidator(XmlSchemaObject? partialValidationType) { XmlSchemaValidator findTypeValidator = new XmlSchemaValidator(_document.NameTable, _document.Schemas, _nsManager, XmlSchemaValidationFlags.None); findTypeValidator.ValidationEventHandler += new ValidationEventHandler(TypeFinderCallBack); @@ -779,10 +794,11 @@ namespace System.Xml { //If we walked up to the root and no schemaInfo was there, start validating from root findTypeValidator.Initialize(); } + return findTypeValidator; } - private void TypeFinderCallBack(object sender, ValidationEventArgs arg) + private void TypeFinderCallBack(object? sender, ValidationEventArgs arg) { if (arg.Severity == XmlSeverityType.Error) { @@ -790,13 +806,13 @@ namespace System.Xml } } - private void InternalValidationCallBack(object sender, ValidationEventArgs arg) + private void InternalValidationCallBack(object? sender, ValidationEventArgs arg) { if (arg.Severity == XmlSeverityType.Error) { _isValid = false; } - XmlSchemaValidationException ex = arg.Exception as XmlSchemaValidationException; + XmlSchemaValidationException? ex = arg.Exception as XmlSchemaValidationException; Debug.Assert(ex != null); ex.SetSourceObject(_currentNode); if (_eventHandler != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs index ee8b229..8012cea 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -57,13 +58,13 @@ namespace System.Xml private readonly DocumentXmlWriterType _type; // writer type private readonly XmlNode _start; // context node private readonly XmlDocument _document; // context document - private XmlNamespaceManager _namespaceManager; // context namespace manager + private XmlNamespaceManager? _namespaceManager; // context namespace manager private State _state; // current state - private XmlNode _write; // current node + private XmlNode? _write; // current node private readonly List _fragment; // top level node cache private readonly XmlWriterSettings _settings; // wrapping writer settings - private DocumentXPathNavigator _navigator; // context for replace - private XmlNode _end; // context for replace + private DocumentXPathNavigator? _navigator; // context for replace + private XmlNode? _end; // context for replace public DocumentXmlWriter(DocumentXmlWriterType type, XmlNode start, XmlDocument document) { @@ -81,7 +82,7 @@ namespace System.Xml _settings.ReadOnly = true; } - public XmlNamespaceManager NamespaceManager + public XmlNamespaceManager? NamespaceManager { set { @@ -97,7 +98,7 @@ namespace System.Xml } } - public DocumentXPathNavigator Navigator + public DocumentXPathNavigator? Navigator { set { @@ -126,9 +127,9 @@ namespace System.Xml internal override void WriteXmlDeclaration(string xmldecl) { VerifyState(Method.WriteXmlDeclaration); - string version, encoding, standalone; + string? version, encoding, standalone; XmlLoader.ParseXmlDeclarationValue(xmldecl, out version, out encoding, out standalone); - XmlNode node = _document.CreateXmlDeclaration(version, encoding, standalone); + XmlNode node = _document.CreateXmlDeclaration(version!, encoding, standalone); AddChild(node, _write); } @@ -147,14 +148,14 @@ namespace System.Xml VerifyState(Method.WriteEndDocument); } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { VerifyState(Method.WriteDocType); XmlNode node = _document.CreateDocumentType(name, pubid, sysid, subset); AddChild(node, _write); } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { VerifyState(Method.WriteStartElement); XmlNode node = _document.CreateElement(prefix, localName, ns); @@ -169,6 +170,7 @@ namespace System.Xml { throw new InvalidOperationException(); } + _write = _write.ParentNode; } @@ -180,11 +182,12 @@ namespace System.Xml public override void WriteFullEndElement() { VerifyState(Method.WriteFullEndElement); - XmlElement elem = _write as XmlElement; + XmlElement? elem = _write as XmlElement; if (elem == null) { throw new InvalidOperationException(); } + elem.IsEmpty = false; _write = elem.ParentNode; } @@ -199,7 +202,7 @@ namespace System.Xml // nop } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { VerifyState(Method.WriteStartAttribute); XmlAttribute attr = _document.CreateAttribute(prefix, localName, ns); @@ -210,16 +213,18 @@ namespace System.Xml public override void WriteEndAttribute() { VerifyState(Method.WriteEndAttribute); - XmlAttribute attr = _write as XmlAttribute; + XmlAttribute? attr = _write as XmlAttribute; if (attr == null) { throw new InvalidOperationException(); } + if (!attr.HasChildNodes) { XmlNode node = _document.CreateTextNode(string.Empty); AddChild(node, attr); } + _write = attr.OwnerElement; } @@ -250,6 +255,7 @@ namespace System.Xml { attr = _document.CreateAttribute(_document.strXmlns, prefix, _document.strReservedXmlns); } + AddAttribute(attr, _write); _write = attr; } @@ -257,20 +263,22 @@ namespace System.Xml internal override void WriteEndNamespaceDeclaration() { VerifyState(Method.WriteEndNamespaceDeclaration); - XmlAttribute attr = _write as XmlAttribute; + XmlAttribute? attr = _write as XmlAttribute; if (attr == null) { throw new InvalidOperationException(); } + if (!attr.HasChildNodes) { XmlNode node = _document.CreateTextNode(string.Empty); AddChild(node, attr); } + _write = attr.OwnerElement; } - public override void WriteCData(string text) + public override void WriteCData(string? text) { VerifyState(Method.WriteCData); XmlConvert.VerifyCharData(text, ExceptionType.ArgumentException); @@ -278,7 +286,7 @@ namespace System.Xml AddChild(node, _write); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { VerifyState(Method.WriteComment); XmlConvert.VerifyCharData(text, ExceptionType.ArgumentException); @@ -286,11 +294,11 @@ namespace System.Xml AddChild(node, _write); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { VerifyState(Method.WriteProcessingInstruction); XmlConvert.VerifyCharData(text, ExceptionType.ArgumentException); - XmlNode node = _document.CreateProcessingInstruction(name, text); + XmlNode node = _document.CreateProcessingInstruction(name, text!); AddChild(node, _write); } @@ -307,7 +315,7 @@ namespace System.Xml WriteString(char.ToString(ch)); } - public override void WriteWhitespace(string text) + public override void WriteWhitespace(string? text) { VerifyState(Method.WriteWhitespace); XmlConvert.VerifyCharData(text, ExceptionType.ArgumentException); @@ -318,7 +326,7 @@ namespace System.Xml } } - public override void WriteString(string text) + public override void WriteString(string? text) { VerifyState(Method.WriteString); XmlConvert.VerifyCharData(text, ExceptionType.ArgumentException); @@ -363,15 +371,17 @@ namespace System.Xml switch (_type) { case DocumentXmlWriterType.InsertSiblingAfter: - XmlNode parent = _start.ParentNode; + XmlNode? parent = _start.ParentNode; if (parent == null) { throw new InvalidOperationException(SR.Xpn_MissingParent); } + for (int i = _fragment.Count - 1; i >= 0; i--) { parent.InsertAfter(_fragment[i], _start); } + break; case DocumentXmlWriterType.InsertSiblingBefore: parent = _start.ParentNode; @@ -379,22 +389,26 @@ namespace System.Xml { throw new InvalidOperationException(SR.Xpn_MissingParent); } + for (int i = 0; i < _fragment.Count; i++) { parent.InsertBefore(_fragment[i], _start); } + break; case DocumentXmlWriterType.PrependChild: for (int i = _fragment.Count - 1; i >= 0; i--) { _start.PrependChild(_fragment[i]); } + break; case DocumentXmlWriterType.AppendChild: for (int i = 0; i < _fragment.Count; i++) { _start.AppendChild(_fragment[i]); } + break; case DocumentXmlWriterType.AppendAttribute: CloseWithAppendAttribute(); @@ -404,6 +418,7 @@ namespace System.Xml { throw new InvalidOperationException(SR.Xpn_NoContent); } + CloseWithReplaceToFollowingSibling(); break; } @@ -416,12 +431,12 @@ namespace System.Xml private void CloseWithAppendAttribute() { - XmlElement elem = _start as XmlElement; + XmlElement? elem = _start as XmlElement; Debug.Assert(elem != null); XmlAttributeCollection attrs = elem.Attributes; for (int i = 0; i < _fragment.Count; i++) { - XmlAttribute attr = _fragment[i] as XmlAttribute; + XmlAttribute? attr = _fragment[i] as XmlAttribute; Debug.Assert(attr != null); int offset = attrs.FindNodeOffsetNS(attr); if (offset != -1 @@ -432,7 +447,7 @@ namespace System.Xml } for (int i = 0; i < _fragment.Count; i++) { - XmlAttribute attr = _fragment[i] as XmlAttribute; + XmlAttribute? attr = _fragment[i] as XmlAttribute; Debug.Assert(attr != null); attrs.Append(attr); } @@ -440,11 +455,12 @@ namespace System.Xml private void CloseWithReplaceToFollowingSibling() { - XmlNode parent = _start.ParentNode; + XmlNode? parent = _start.ParentNode; if (parent == null) { throw new InvalidOperationException(SR.Xpn_MissingParent); } + if (_start != _end) { if (!DocumentXPathNavigator.IsFollowingSibling(_start, _end)) @@ -455,15 +471,18 @@ namespace System.Xml { throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly); } + DocumentXPathNavigator.DeleteToFollowingSibling(_start.NextSibling, _end); } + XmlNode fragment0 = _fragment[0]; parent.ReplaceChild(fragment0, _start); for (int i = _fragment.Count - 1; i >= 1; i--) { parent.InsertAfter(_fragment[i], fragment0); } - _navigator.ResetPosition(fragment0); + + _navigator!.ResetPosition(fragment0); } public override void Flush() @@ -473,20 +492,20 @@ namespace System.Xml IDictionary IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { - return _namespaceManager.GetNamespacesInScope(scope); + return _namespaceManager!.GetNamespacesInScope(scope); } - string IXmlNamespaceResolver.LookupNamespace(string prefix) + string? IXmlNamespaceResolver.LookupNamespace(string prefix) { - return _namespaceManager.LookupNamespace(prefix); + return _namespaceManager!.LookupNamespace(prefix); } - string IXmlNamespaceResolver.LookupPrefix(string namespaceName) + string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) { - return _namespaceManager.LookupPrefix(namespaceName); + return _namespaceManager!.LookupPrefix(namespaceName); } - private void AddAttribute(XmlAttribute attr, XmlNode parent) + private void AddAttribute(XmlAttribute attr, XmlNode? parent) { if (parent == null) { @@ -494,16 +513,17 @@ namespace System.Xml } else { - XmlElement elem = parent as XmlElement; + XmlElement? elem = parent as XmlElement; if (elem == null) { throw new InvalidOperationException(); } + elem.Attributes.Append(attr); } } - private void AddChild(XmlNode node, XmlNode parent) + private void AddChild(XmlNode node, XmlNode? parent) { if (parent == null) { @@ -523,11 +543,12 @@ namespace System.Xml { case DocumentXmlWriterType.InsertSiblingAfter: case DocumentXmlWriterType.InsertSiblingBefore: - XmlNode parent = _start.ParentNode; + XmlNode? parent = _start.ParentNode; if (parent != null) { nodeType = parent.NodeType; } + if (nodeType == XmlNodeType.Document) { return State.Prolog; @@ -536,6 +557,7 @@ namespace System.Xml { return State.Fragment; } + break; case DocumentXmlWriterType.PrependChild: case DocumentXmlWriterType.AppendChild: @@ -548,6 +570,7 @@ namespace System.Xml { return State.Fragment; } + break; case DocumentXmlWriterType.AppendAttribute: return State.Attribute; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs index 593cae9..6e18795 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Diagnostics; using System.Xml.Schema; @@ -26,7 +27,7 @@ namespace System.Xml Debug.Assert((_entries.Length & _mask) == 0); // entries.Length must be a power of two } - public XmlName GetName(string prefix, string localName, string ns, IXmlSchemaInfo schemaInfo) + public XmlName? GetName(string? prefix, string localName, string? ns, IXmlSchemaInfo? schemaInfo) { if (prefix == null) { @@ -56,7 +57,7 @@ namespace System.Xml return null; } - public XmlName AddName(string prefix, string localName, string ns, IXmlSchemaInfo schemaInfo) + public XmlName AddName(string? prefix, string localName, string? ns, IXmlSchemaInfo? schemaInfo) { if (prefix == null) { @@ -118,6 +119,7 @@ namespace System.Xml name = tmp; } } + _entries = newEntries; _mask = newMask; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs index ccc26c0..5202676 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { using System.Xml.XPath; @@ -10,14 +11,14 @@ namespace System.Xml internal class XPathNodeList : XmlNodeList { - private readonly List _list; + private readonly List _list; private readonly XPathNodeIterator _nodeIterator; private bool _done; public XPathNodeList(XPathNodeIterator nodeIterator) { _nodeIterator = nodeIterator; - _list = new List(); + _list = new List(); _done = false; } @@ -62,7 +63,7 @@ namespace System.Xml return count; } - public override XmlNode Item(int index) + public override XmlNode? Item(int index) { if (_list.Count <= index) { @@ -72,6 +73,7 @@ namespace System.Xml { return null; } + return _list[index]; } @@ -111,7 +113,7 @@ namespace System.Xml return _valid; } - public object Current + public object? Current { get { @@ -119,6 +121,7 @@ namespace System.Xml { return _list[_index]; } + return null; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs index a8d6230..24e11bd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs @@ -1,10 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; using System.Xml.XPath; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -13,7 +15,7 @@ namespace System.Xml public class XmlAttribute : XmlNode { private XmlName _name; - private XmlLinkedNode _lastChild; + private XmlLinkedNode? _lastChild; internal XmlAttribute(XmlName name, XmlDocument doc) : base(doc) { @@ -35,7 +37,7 @@ namespace System.Xml get { return _name.HashCode; } } - protected internal XmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc) + protected internal XmlAttribute(string? prefix, string localName, string? namespaceURI, XmlDocument doc) : this(doc.AddAttrXmlName(prefix, localName, namespaceURI, null), doc) { } @@ -58,7 +60,7 @@ namespace System.Xml } // Gets the parent of this node (for nodes that can have parents). - public override XmlNode ParentNode + public override XmlNode? ParentNode { get { return null; } } @@ -104,10 +106,11 @@ namespace System.Xml } // Gets or sets the value of the node. + [AllowNull] public override string Value { get { return InnerText; } - set { InnerText = value; } //use InnerText which has perf optimization + set { InnerText = value!; } //use InnerText which has perf optimization } public override IXmlSchemaInfo SchemaInfo @@ -140,18 +143,19 @@ namespace System.Xml XmlDocument ownerDocument = OwnerDocument; if (ownerDocument.DtdSchemaInfo != null) { // DTD exists - XmlElement ownerElement = OwnerElement; + XmlElement? ownerElement = OwnerElement; if (ownerElement != null) { return ownerElement.Attributes.PrepareParentInElementIdAttrMap(Prefix, LocalName); } } + return false; } internal void ResetOwnerElementInElementIdAttrMap(string oldInnerText) { - XmlElement ownerElement = OwnerElement; + XmlElement? ownerElement = OwnerElement; if (ownerElement != null) { ownerElement.Attributes.ResetParentInElementIdAttrMap(oldInnerText, InnerText); @@ -166,7 +170,7 @@ namespace System.Xml //the function is provided only at Load time to speed up Load process internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { - XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this); + XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); @@ -202,7 +206,7 @@ namespace System.Xml return newNode; } - internal override XmlLinkedNode LastNode + internal override XmlLinkedNode? LastNode { get { return _lastChild; } set { _lastChild = value; } @@ -219,12 +223,12 @@ namespace System.Xml get { return true; } } - public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) + public override XmlNode? InsertBefore(XmlNode newChild, XmlNode? refChild) { - XmlNode node; + XmlNode? node; if (PrepareOwnerElementInElementIdAttrMap()) { - string innerText = InnerText; + string? innerText = InnerText; node = base.InsertBefore(newChild, refChild); ResetOwnerElementInElementIdAttrMap(innerText); } @@ -232,15 +236,16 @@ namespace System.Xml { node = base.InsertBefore(newChild, refChild); } + return node; } - public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) + public override XmlNode? InsertAfter(XmlNode newChild, XmlNode? refChild) { - XmlNode node; + XmlNode? node; if (PrepareOwnerElementInElementIdAttrMap()) { - string innerText = InnerText; + string? innerText = InnerText; node = base.InsertAfter(newChild, refChild); ResetOwnerElementInElementIdAttrMap(innerText); } @@ -248,6 +253,7 @@ namespace System.Xml { node = base.InsertAfter(newChild, refChild); } + return node; } @@ -256,7 +262,7 @@ namespace System.Xml XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { - string innerText = InnerText; + string? innerText = InnerText; node = base.ReplaceChild(newChild, oldChild); ResetOwnerElementInElementIdAttrMap(innerText); } @@ -272,7 +278,7 @@ namespace System.Xml XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { - string innerText = InnerText; + string? innerText = InnerText; node = base.RemoveChild(oldChild); ResetOwnerElementInElementIdAttrMap(innerText); } @@ -283,12 +289,12 @@ namespace System.Xml return node; } - public override XmlNode PrependChild(XmlNode newChild) + public override XmlNode? PrependChild(XmlNode newChild) { - XmlNode node; + XmlNode? node; if (PrepareOwnerElementInElementIdAttrMap()) { - string innerText = InnerText; + string? innerText = InnerText; node = base.PrependChild(newChild); ResetOwnerElementInElementIdAttrMap(innerText); } @@ -296,15 +302,16 @@ namespace System.Xml { node = base.PrependChild(newChild); } + return node; } - public override XmlNode AppendChild(XmlNode newChild) + public override XmlNode? AppendChild(XmlNode newChild) { - XmlNode node; + XmlNode? node; if (PrepareOwnerElementInElementIdAttrMap()) { - string innerText = InnerText; + string? innerText = InnerText; node = base.AppendChild(newChild); ResetOwnerElementInElementIdAttrMap(innerText); } @@ -312,13 +319,14 @@ namespace System.Xml { node = base.AppendChild(newChild); } + return node; } // DOM Level 2 // Gets the XmlElement node that contains this attribute. - public virtual XmlElement OwnerElement + public virtual XmlElement? OwnerElement { get { @@ -348,7 +356,7 @@ namespace System.Xml // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { - for (XmlNode node = FirstChild; node != null; node = node.NextSibling) + for (XmlNode? node = FirstChild; node != null; node = node.NextSibling) { node.WriteTo(w); } @@ -364,7 +372,7 @@ namespace System.Xml } } - internal override void SetParent(XmlNode node) + internal override void SetParent(XmlNode? node) { this.parentNode = node; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs index 6273f18..b2fd07d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs @@ -1,8 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -32,7 +34,7 @@ namespace System.Xml // Gets the attribute with the specified name. [System.Runtime.CompilerServices.IndexerName("ItemOf")] - public XmlAttribute this[string name] + public XmlAttribute? this[string name] { get { @@ -55,7 +57,7 @@ namespace System.Xml // Gets the attribute with the specified LocalName and NamespaceUri. [System.Runtime.CompilerServices.IndexerName("ItemOf")] - public XmlAttribute this[string localName, string namespaceURI] + public XmlAttribute? this[string localName, string? namespaceURI] { get { @@ -90,6 +92,7 @@ namespace System.Xml return i; } } + return -1; } @@ -109,7 +112,8 @@ namespace System.Xml } // Adds a XmlNode using its Name property - public override XmlNode SetNamedItem(XmlNode node) + [return: NotNullIfNotNull("node")] + public override XmlNode? SetNamedItem(XmlNode? node) { if (node == null) return null; @@ -170,7 +174,7 @@ namespace System.Xml } // Inserts the specified attribute immediately before the specified reference attribute. - public XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute refNode) + public XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute? refNode) { if (newNode == refNode) return newNode; @@ -199,7 +203,7 @@ namespace System.Xml } // Inserts the specified attribute immediately after the specified reference attribute. - public XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute refNode) + public XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute? refNode) { if (newNode == refNode) return newNode; @@ -228,7 +232,7 @@ namespace System.Xml } // Removes the specified attribute node from the map. - public XmlAttribute Remove(XmlAttribute node) + public XmlAttribute? Remove(XmlAttribute? node) { int cNodes = nodes.Count; for (int offset = 0; offset < cNodes; offset++) @@ -239,11 +243,12 @@ namespace System.Xml return node; } } + return null; } // Removes the attribute node with the specified index from the map. - public XmlAttribute RemoveAt(int i) + public XmlAttribute? RemoveAt(int i) { if (i < 0 || i >= Count) return null; @@ -315,26 +320,28 @@ namespace System.Xml Debug.Assert(retNode is XmlAttribute); RemoveParentFromElementIdAttrMap((XmlAttribute)retNode); // after remove the attribute, we need to check if a default attribute node should be created and inserted into the tree - XmlAttribute defattr = parent.OwnerDocument.GetDefaultAttribute((XmlElement)parent, retNode.Prefix, retNode.LocalName, retNode.NamespaceURI); + XmlAttribute? defattr = parent.OwnerDocument!.GetDefaultAttribute((XmlElement)parent, retNode.Prefix, retNode.LocalName, retNode.NamespaceURI); if (defattr != null) InsertNodeAt(i, defattr); + return retNode; } internal void Detach(XmlAttribute attr) { - attr.OwnerElement.Attributes.Remove(attr); + attr.OwnerElement!.Attributes.Remove(attr); } //insert the parent element node into the map internal void InsertParentIntoElementIdAttrMap(XmlAttribute attr) { - XmlElement parentElem = parent as XmlElement; + XmlElement? parentElem = parent as XmlElement; if (parentElem != null) { if (parent.OwnerDocument == null) return; - XmlName attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); + + XmlName? attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) { parent.OwnerDocument.AddElementWithId(attr.Value, parentElem); //add the element into the hashtable @@ -345,12 +352,13 @@ namespace System.Xml //remove the parent element node from the map when the ID attribute is removed internal void RemoveParentFromElementIdAttrMap(XmlAttribute attr) { - XmlElement parentElem = parent as XmlElement; + XmlElement? parentElem = parent as XmlElement; if (parentElem != null) { if (parent.OwnerDocument == null) return; - XmlName attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); + + XmlName? attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) { parent.OwnerDocument.RemoveElementWithId(attr.Value, parentElem); //remove the element from the hashtable @@ -375,25 +383,26 @@ namespace System.Xml internal bool PrepareParentInElementIdAttrMap(string attrPrefix, string attrLocalName) { - XmlElement parentElem = parent as XmlElement; + XmlElement? parentElem = parent as XmlElement; Debug.Assert(parentElem != null); - XmlDocument doc = parent.OwnerDocument; + XmlDocument? doc = parent.OwnerDocument; Debug.Assert(doc != null); //The returned attrname if not null is the name with namespaceURI being set to string.Empty //Because DTD doesn't support namespaceURI so all comparisons are based on no namespaceURI (string.Empty); - XmlName attrname = doc.GetIDInfoByElement(parentElem.XmlName); + XmlName? attrname = doc.GetIDInfoByElement(parentElem.XmlName); if (attrname != null && attrname.Prefix == attrPrefix && attrname.LocalName == attrLocalName) { return true; } + return false; } internal void ResetParentInElementIdAttrMap(string oldVal, string newVal) { - XmlElement parentElem = parent as XmlElement; + XmlElement? parentElem = parent as XmlElement; Debug.Assert(parentElem != null); - XmlDocument doc = parent.OwnerDocument; + XmlDocument? doc = parent.OwnerDocument; Debug.Assert(doc != null); doc.RemoveElementWithId(oldVal, parentElem); //add the element into the hashtable doc.AddElementWithId(newVal, parentElem); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs index b2f52d5..86f65d6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; using System.Xml.XPath; @@ -10,7 +11,7 @@ namespace System.Xml // interpreted as markup language. public class XmlCDataSection : XmlCharacterData { - protected internal XmlCDataSection(string data, XmlDocument doc) : base(data, doc) + protected internal XmlCDataSection(string? data, XmlDocument doc) : base(data, doc) { } @@ -19,7 +20,7 @@ namespace System.Xml { get { - return OwnerDocument.strCDataSectionName; + return OwnerDocument!.strCDataSectionName; } } @@ -28,7 +29,7 @@ namespace System.Xml { get { - return OwnerDocument.strCDataSectionName; + return OwnerDocument!.strCDataSectionName; } } @@ -41,11 +42,11 @@ namespace System.Xml } } - public override XmlNode ParentNode + public override XmlNode? ParentNode { get { - switch (parentNode.NodeType) + switch (parentNode!.NodeType) { case XmlNodeType.Document: return null; @@ -53,11 +54,12 @@ namespace System.Xml case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: - XmlNode parent = parentNode.parentNode; + XmlNode parent = parentNode.parentNode!; while (parent.IsText) { - parent = parent.parentNode; + parent = parent.parentNode!; } + return parent; default: return parentNode; @@ -100,14 +102,15 @@ namespace System.Xml } } - public override XmlNode PreviousText + public override XmlNode? PreviousText { get { - if (parentNode.IsText) + if (parentNode != null && parentNode.IsText) { return parentNode; } + return null; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs index c03e0e2..f5d7f61 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs @@ -1,7 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Text; using System.Xml.XPath; @@ -10,16 +12,16 @@ namespace System.Xml // Provides text-manipulation methods that are used by several classes. public abstract class XmlCharacterData : XmlLinkedNode { - private string _data; + private string? _data; //base(doc) will throw exception if doc is null. - protected internal XmlCharacterData(string data, XmlDocument doc) : base(doc) + protected internal XmlCharacterData(string? data, XmlDocument doc) : base(doc) { _data = data; } // Gets or sets the value of the node. - public override string Value + public override string? Value { get { return Data; } set { Data = value; } @@ -29,11 +31,12 @@ namespace System.Xml // all its children. public override string InnerText { - get { return Value; } + get { return Value!; } set { Value = value; } } // Contains this node's data. + [AllowNull] public virtual string Data { get @@ -50,8 +53,8 @@ namespace System.Xml set { - XmlNode parent = ParentNode; - XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, value, XmlNodeChangedAction.Change); + XmlNode? parent = ParentNode; + XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, value, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); @@ -86,20 +89,21 @@ namespace System.Xml { count = len - offset; } - return _data.Substring(offset, count); + + return _data!.Substring(offset, count); } return string.Empty; } // Appends the specified string to the end of the character // data of the node. - public virtual void AppendData(string strData) + public virtual void AppendData(string? strData) { - XmlNode parent = ParentNode; + XmlNode? parent = ParentNode; int capacity = _data != null ? _data.Length : 0; if (strData != null) capacity += strData.Length; string newValue = new StringBuilder(capacity).Append(_data).Append(strData).ToString(); - XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); + XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); @@ -111,13 +115,13 @@ namespace System.Xml } // Insert the specified string at the specified character offset. - public virtual void InsertData(int offset, string strData) + public virtual void InsertData(int offset, string? strData) { - XmlNode parent = ParentNode; + XmlNode? parent = ParentNode; int capacity = _data != null ? _data.Length : 0; if (strData != null) capacity += strData.Length; string newValue = new StringBuilder(capacity).Append(_data).Insert(offset, strData).ToString(); - XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); + XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); @@ -142,8 +146,8 @@ namespace System.Xml } string newValue = new StringBuilder(_data).Remove(offset, count).ToString(); - XmlNode parent = ParentNode; - XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); + XmlNode? parent = ParentNode; + XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); @@ -156,7 +160,7 @@ namespace System.Xml // Replace the specified number of characters starting at the specified offset with the // specified string. - public virtual void ReplaceData(int offset, int count, string strData) + public virtual void ReplaceData(int offset, int count, string? strData) { int len = _data != null ? _data.Length : 0; if (len > 0) @@ -170,8 +174,8 @@ namespace System.Xml StringBuilder temp = new StringBuilder(_data).Remove(offset, count); string newValue = temp.Insert(offset, strData).ToString(); - XmlNode parent = ParentNode; - XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); + XmlNode? parent = ParentNode; + XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); @@ -182,7 +186,7 @@ namespace System.Xml AfterEvent(args); } - internal bool CheckOnData(string data) + internal bool CheckOnData(string? data) { return XmlCharType.Instance.IsOnlyWhitespace(data); } @@ -194,10 +198,11 @@ namespace System.Xml //changes according to the siblings nodetype and will contain the correct //nodetype when it returns. - Debug.Assert(XmlDocument.IsTextNode(node.NodeType) || (node.ParentNode != null && node.ParentNode.NodeType == XmlNodeType.EntityReference)); - while (node != null) + XmlNode? n = node; + Debug.Assert(XmlDocument.IsTextNode(n.NodeType) || (n.ParentNode != null && n.ParentNode.NodeType == XmlNodeType.EntityReference)); + while (n != null) { - switch (node.NodeType) + switch (n.NodeType) { case XmlNodeType.Whitespace: break; @@ -209,7 +214,7 @@ namespace System.Xml xnt = XPathNodeType.Text; return false; case XmlNodeType.EntityReference: - if (!DecideXPNodeTypeForTextNodes(node.FirstChild, ref xnt)) + if (!DecideXPNodeTypeForTextNodes(n.FirstChild!, ref xnt)) { return false; } @@ -217,7 +222,7 @@ namespace System.Xml default: return false; } - node = node.NextSibling; + n = n.NextSibling; } return true; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs index a5011a9..463b966 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; namespace System.Xml @@ -8,7 +9,7 @@ namespace System.Xml internal sealed class XmlChildEnumerator : IEnumerator { internal XmlNode container; - internal XmlNode child; + internal XmlNode? child; internal bool isFirst; internal XmlChildEnumerator(XmlNode container) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs index 39bf493..865f5b1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; namespace System.Xml @@ -14,16 +15,18 @@ namespace System.Xml _container = container; } - public override XmlNode Item(int i) + public override XmlNode? Item(int i) { // Out of range indexes return a null XmlNode if (i < 0) return null; - for (XmlNode n = _container.FirstChild; n != null; n = n.NextSibling, i--) + + for (XmlNode? n = _container.FirstChild; n != null; n = n.NextSibling, i--) { if (i == 0) return n; } + return null; } @@ -32,10 +35,11 @@ namespace System.Xml get { int c = 0; - for (XmlNode n = _container.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = _container.FirstChild; n != null; n = n.NextSibling) { c++; } + return c; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs index 2f52524..d9ea593 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; using System.Xml.XPath; @@ -9,20 +10,20 @@ namespace System.Xml // Represents the content of an XML comment. public class XmlComment : XmlCharacterData { - protected internal XmlComment(string comment, XmlDocument doc) : base(comment, doc) + protected internal XmlComment(string? comment, XmlDocument doc) : base(comment, doc) { } // Gets the name of the node. public override string Name { - get { return OwnerDocument.strCommentName; } + get { return OwnerDocument!.strCommentName; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { - get { return OwnerDocument.strCommentName; } + get { return OwnerDocument!.strCommentName; } } // Gets the type of the current node. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs index b4e9251..4544ca7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs @@ -1,7 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; @@ -17,7 +19,7 @@ namespace System.Xml private string _encoding; private string _standalone; - protected internal XmlDeclaration(string version, string encoding, string standalone, XmlDocument doc) : base(doc) + protected internal XmlDeclaration(string version, string? encoding, string? standalone, XmlDocument doc) : base(doc) { if (!IsValidXmlVersion(version)) throw new ArgumentException(SR.Xdom_Version); @@ -34,21 +36,26 @@ namespace System.Xml public string Version { get { return _version; } + [MemberNotNull(nameof(_version))] internal set { _version = value; } } // Specifies the value of the encoding attribute, as for // + [AllowNull] public string Encoding { get { return _encoding; } + [MemberNotNull(nameof(_encoding))] set { _encoding = ((value == null) ? string.Empty : value); } } // Specifies the value of the standalone attribute. + [AllowNull] public string Standalone { get { return _standalone; } + [MemberNotNull(nameof(_standalone))] set { if (value == null) @@ -60,10 +67,10 @@ namespace System.Xml } } - public override string Value + public override string? Value { get { return InnerText; } - set { InnerText = value; } + set { InnerText = value!; } } @@ -89,17 +96,18 @@ namespace System.Xml strb.Append(Standalone); strb.Append('"'); } + return StringBuilderCache.GetStringAndRelease(strb); } set { - string tempVersion = null; - string tempEncoding = null; - string tempStandalone = null; + string? tempVersion = null; + string? tempEncoding = null; + string? tempStandalone = null; string orgEncoding = this.Encoding; string orgStandalone = this.Standalone; - string orgVersion = this.Version; + string? orgVersion = this.Version; XmlLoader.ParseXmlDeclarationValue(value, out tempVersion, out tempEncoding, out tempStandalone); @@ -107,7 +115,7 @@ namespace System.Xml { if (tempVersion != null && !IsValidXmlVersion(tempVersion)) throw new ArgumentException(SR.Xdom_Version); - Version = tempVersion; + Version = tempVersion!; if (tempEncoding != null) Encoding = tempEncoding; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs index 7ced05f..a254bee 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -12,6 +13,7 @@ using System.Xml.XPath; using System.Security; using System.Globalization; using System.Runtime.Versioning; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -72,24 +74,24 @@ namespace System.Xml private readonly XmlImplementation _implementation; private readonly DomNameTable _domNameTable; // hash table of XmlName - private XmlLinkedNode _lastChild; - private XmlNamedNodeMap _entities; - private Hashtable _htElementIdMap; - private Hashtable _htElementIDAttrDecl; //key: id; object: the ArrayList of the elements that have the same id (connected or disconnected) - private SchemaInfo _schemaInfo; - private XmlSchemaSet _schemas; // schemas associated with the cache + private XmlLinkedNode? _lastChild; + private XmlNamedNodeMap? _entities; + private Hashtable? _htElementIdMap; + private Hashtable? _htElementIDAttrDecl; //key: id; object: the ArrayList of the elements that have the same id (connected or disconnected) + private SchemaInfo? _schemaInfo; + private XmlSchemaSet? _schemas; // schemas associated with the cache private bool _reportValidity; //This variable represents the actual loading status. Since, IsLoading will //be manipulated sometimes for adding content to EntityReference this variable //has been added which would always represent the loading status of document. private bool _actualLoadingStatus; - private XmlNodeChangedEventHandler _onNodeInsertingDelegate; - private XmlNodeChangedEventHandler _onNodeInsertedDelegate; - private XmlNodeChangedEventHandler _onNodeRemovingDelegate; - private XmlNodeChangedEventHandler _onNodeRemovedDelegate; - private XmlNodeChangedEventHandler _onNodeChangingDelegate; - private XmlNodeChangedEventHandler _onNodeChangedDelegate; + private XmlNodeChangedEventHandler? _onNodeInsertingDelegate; + private XmlNodeChangedEventHandler? _onNodeInsertedDelegate; + private XmlNodeChangedEventHandler? _onNodeRemovingDelegate; + private XmlNodeChangedEventHandler? _onNodeRemovedDelegate; + private XmlNodeChangedEventHandler? _onNodeChangingDelegate; + private XmlNodeChangedEventHandler? _onNodeChangedDelegate; // false if there are no ent-ref present, true if ent-ref nodes are or were present (i.e. if all ent-ref were removed, the doc will not clear this flag) internal bool fEntRefNodesPresent; @@ -118,11 +120,11 @@ namespace System.Xml internal string baseURI; - private XmlResolver _resolver; + private XmlResolver? _resolver; internal bool bSetResolver; internal object objLock; - private XmlAttribute _namespaceXml; + private XmlAttribute? _namespaceXml; internal static EmptyEnumerator EmptyEnumerator = new EmptyEnumerator(); internal static IXmlSchemaInfo NotKnownSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.NotKnown); @@ -194,7 +196,7 @@ namespace System.Xml } } - internal SchemaInfo DtdSchemaInfo + internal SchemaInfo? DtdSchemaInfo { get { return _schemaInfo; } set { _schemaInfo = value; } @@ -210,7 +212,7 @@ namespace System.Xml } } - internal XmlName AddXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) + internal XmlName AddXmlName(string? prefix, string localName, string? namespaceURI, IXmlSchemaInfo? schemaInfo) { XmlName n = _domNameTable.AddName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix)); @@ -219,16 +221,16 @@ namespace System.Xml return n; } - internal XmlName GetXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) + internal XmlName? GetXmlName(string? prefix, string localName, string? namespaceURI, IXmlSchemaInfo? schemaInfo) { - XmlName n = _domNameTable.GetName(prefix, localName, namespaceURI, schemaInfo); + XmlName? n = _domNameTable.GetName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert(n == null || ((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix))); Debug.Assert(n == null || n.LocalName == localName); Debug.Assert(n == null || ((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI))); return n; } - internal XmlName AddAttrXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) + internal XmlName AddAttrXmlName(string? prefix, string localName, string? namespaceURI, IXmlSchemaInfo? schemaInfo) { XmlName xmlName = AddXmlName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert((prefix == null) ? (xmlName.Prefix.Length == 0) : (prefix == xmlName.Prefix)); @@ -262,20 +264,20 @@ namespace System.Xml return false; } - private XmlName GetIDInfoByElement_(XmlName eleName) + private XmlName? GetIDInfoByElement_(XmlName eleName) { //When XmlDocument is getting the IDAttribute for a given element, //we need only compare the prefix and localname of element.XmlName with //the registered htElementIDAttrDecl. - XmlName newName = GetXmlName(eleName.Prefix, eleName.LocalName, string.Empty, null); + XmlName? newName = GetXmlName(eleName.Prefix, eleName.LocalName, string.Empty, null); if (newName != null) { - return (XmlName)(_htElementIDAttrDecl[newName]); + return (XmlName?)(_htElementIDAttrDecl![newName]); } return null; } - internal XmlName GetIDInfoByElement(XmlName eleName) + internal XmlName? GetIDInfoByElement(XmlName eleName) { if (_htElementIDAttrDecl == null) return null; @@ -283,7 +285,7 @@ namespace System.Xml return GetIDInfoByElement_(eleName); } - private WeakReference GetElement(ArrayList elementList, XmlElement elem) + private WeakReference? GetElement(ArrayList elementList, XmlElement elem) { ArrayList gcElemRefs = new ArrayList(); foreach (WeakReference elemRef in elementList) @@ -293,7 +295,7 @@ namespace System.Xml gcElemRefs.Add(elemRef); else { - if ((XmlElement)(elemRef.Target) == elem) + if ((XmlElement?)(elemRef.Target) == elem) return elemRef; } } @@ -316,7 +318,7 @@ namespace System.Xml else { // there are other element(s) that has the same id - ArrayList elementList = (ArrayList)(_htElementIdMap[id]); + ArrayList elementList = (ArrayList)(_htElementIdMap[id]!); if (GetElement(elementList, elem) == null) elementList.Add(new WeakReference(elem)); } @@ -326,8 +328,8 @@ namespace System.Xml { if (_htElementIdMap != null && _htElementIdMap.Contains(id)) { - ArrayList elementList = (ArrayList)(_htElementIdMap[id]); - WeakReference elemRef = GetElement(elementList, elem); + ArrayList elementList = (ArrayList)(_htElementIdMap[id]!); + WeakReference? elemRef = GetElement(elementList, elem); if (elemRef != null) { elementList.Remove(elemRef); @@ -355,24 +357,24 @@ namespace System.Xml get { return XmlNodeType.Document; } } - public override XmlNode ParentNode + public override XmlNode? ParentNode { get { return null; } } // Gets the node for the DOCTYPE declaration. - public virtual XmlDocumentType DocumentType + public virtual XmlDocumentType? DocumentType { - get { return (XmlDocumentType)FindChild(XmlNodeType.DocumentType); } + get { return (XmlDocumentType?)FindChild(XmlNodeType.DocumentType); } } - internal virtual XmlDeclaration Declaration + internal virtual XmlDeclaration? Declaration { get { if (HasChildNodes) { - XmlDeclaration dec = FirstChild as XmlDeclaration; + XmlDeclaration? dec = FirstChild as XmlDeclaration; return dec; } return null; @@ -398,9 +400,9 @@ namespace System.Xml } // Gets the root XmlElement for the document. - public XmlElement DocumentElement + public XmlElement? DocumentElement { - get { return (XmlElement)FindChild(XmlNodeType.Element); } + get { return (XmlElement?)FindChild(XmlNodeType.Element); } } internal override bool IsContainer @@ -408,14 +410,14 @@ namespace System.Xml get { return true; } } - internal override XmlLinkedNode LastNode + internal override XmlLinkedNode? LastNode { get { return _lastChild; } set { _lastChild = value; } } // Gets the XmlDocument that contains this node. - public override XmlDocument OwnerDocument + public override XmlDocument? OwnerDocument { get { return null; } } @@ -447,7 +449,7 @@ namespace System.Xml get { return bSetResolver; } } - internal XmlResolver GetResolver() + internal XmlResolver? GetResolver() { return _resolver; } @@ -460,7 +462,7 @@ namespace System.Xml if (!bSetResolver) bSetResolver = true; - XmlDocumentType dtd = this.DocumentType; + XmlDocumentType? dtd = this.DocumentType; if (dtd != null) { dtd.DtdSchemaInfo = null; @@ -498,12 +500,12 @@ namespace System.Xml } // the function examines all the siblings before the refNode // if any of the nodes has type equals to "nt", return true; otherwise, return false; - private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode refNode) + private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode? refNode) { if (refNode == null) return false; - XmlNode node = null; + XmlNode? node = null; if (refNode.ParentNode != null) node = refNode.ParentNode.FirstChild; while (node != null) @@ -519,9 +521,9 @@ namespace System.Xml // the function examines all the siblings after the refNode // if any of the nodes has the type equals to "nt", return true; otherwise, return false; - private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode refNode) + private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode? refNode) { - XmlNode node = refNode; + XmlNode? node = refNode; while (node != null) { if (node.NodeType == nt) @@ -531,7 +533,7 @@ namespace System.Xml return false; } - internal override bool CanInsertBefore(XmlNode newChild, XmlNode refChild) + internal override bool CanInsertBefore(XmlNode newChild, XmlNode? refChild) { if (refChild == null) refChild = FirstChild; @@ -574,7 +576,7 @@ namespace System.Xml return false; } - internal override bool CanInsertAfter(XmlNode newChild, XmlNode refChild) + internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) { if (refChild == null) refChild = LastChild; @@ -633,20 +635,20 @@ namespace System.Xml } // Creates a XmlCDataSection containing the specified data. - public virtual XmlCDataSection CreateCDataSection(string data) + public virtual XmlCDataSection CreateCDataSection(string? data) { fCDataNodesPresent = true; return new XmlCDataSection(data, this); } // Creates an XmlComment containing the specified data. - public virtual XmlComment CreateComment(string data) + public virtual XmlComment CreateComment(string? data) { return new XmlComment(data, this); } // Returns a new XmlDocumentType object. - public virtual XmlDocumentType CreateDocumentType(string name, string publicId, string systemId, string internalSubset) + public virtual XmlDocumentType CreateDocumentType(string name, string? publicId, string? systemId, string? internalSubset) { return new XmlDocumentType(name, publicId, systemId, internalSubset, this); } @@ -669,8 +671,8 @@ namespace System.Xml internal void AddDefaultAttributes(XmlElement elem) { - SchemaInfo schInfo = DtdSchemaInfo; - SchemaElementDecl ed = GetSchemaElementDecl(elem); + SchemaInfo? schInfo = DtdSchemaInfo; + SchemaElementDecl? ed = GetSchemaElementDecl(elem); if (ed != null && ed.AttDefs != null) { foreach (KeyValuePair attrDefs in ed.AttDefs) @@ -683,7 +685,7 @@ namespace System.Xml string attrPrefix; string attrLocalname = attdef.Name.Name; string attrNamespaceURI = string.Empty; - if (schInfo.SchemaType == SchemaType.DTD) + if (schInfo!.SchemaType == SchemaType.DTD) { attrPrefix = attdef.Name.Namespace; } @@ -699,15 +701,15 @@ namespace System.Xml } } - private SchemaElementDecl GetSchemaElementDecl(XmlElement elem) + private SchemaElementDecl? GetSchemaElementDecl(XmlElement elem) { - SchemaInfo schInfo = DtdSchemaInfo; + SchemaInfo? schInfo = DtdSchemaInfo; if (schInfo != null) { //build XmlQualifiedName used to identify the element schema declaration XmlQualifiedName qname = new XmlQualifiedName(elem.LocalName, schInfo.SchemaType == SchemaType.DTD ? elem.Prefix : elem.NamespaceURI); //get the schema info for the element - SchemaElementDecl elemDecl; + SchemaElementDecl? elemDecl; if (schInfo.ElementDecls.TryGetValue(qname, out elemDecl)) { return elemDecl; @@ -724,7 +726,7 @@ namespace System.Xml //parsing the default value for the default attribute defattr.InnerXml = attdef.DefaultValueRaw; //during the expansion of the tree, the flag could be set to true, we need to set it back. - XmlUnspecifiedAttribute unspAttr = defattr as XmlUnspecifiedAttribute; + XmlUnspecifiedAttribute? unspAttr = defattr as XmlUnspecifiedAttribute; if (unspAttr != null) { unspAttr.SetSpecified(false); @@ -746,32 +748,32 @@ namespace System.Xml } // Creates a XmlDeclaration node with the specified values. - public virtual XmlDeclaration CreateXmlDeclaration(string version, string encoding, string standalone) + public virtual XmlDeclaration CreateXmlDeclaration(string version, string? encoding, string? standalone) { return new XmlDeclaration(version, encoding, standalone, this); } // Creates an XmlText with the specified text. - public virtual XmlText CreateTextNode(string text) + public virtual XmlText CreateTextNode(string? text) { return new XmlText(text, this); } // Creates a XmlSignificantWhitespace node. - public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string text) + public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string? text) { return new XmlSignificantWhitespace(text, this); } - public override XPathNavigator CreateNavigator() + public override XPathNavigator? CreateNavigator() { return CreateNavigator(this); } - protected internal virtual XPathNavigator CreateNavigator(XmlNode node) + protected internal virtual XPathNavigator? CreateNavigator(XmlNode node) { XmlNodeType nodeType = node.NodeType; - XmlNode parent; + XmlNode? parent; XmlNodeType parentType; switch (nodeType) @@ -806,7 +808,7 @@ namespace System.Xml } while (parent != null); } - node = NormalizeText(node); + node = NormalizeText(node)!; break; case XmlNodeType.Whitespace: parent = node.ParentNode; @@ -831,7 +833,7 @@ namespace System.Xml } while (parent != null); } - node = NormalizeText(node); + node = NormalizeText(node)!; break; default: break; @@ -853,9 +855,11 @@ namespace System.Xml } } - private XmlNode NormalizeText(XmlNode n) + private XmlNode? NormalizeText(XmlNode node) { - XmlNode retnode = null; + XmlNode? retnode = null; + XmlNode? n = node; + while (IsTextNode(n.NodeType)) { retnode = n; @@ -887,16 +891,18 @@ namespace System.Xml if (n == null) break; + while (n.NodeType == XmlNodeType.EntityReference) { - n = n.LastChild; + n = n.LastChild!; } } + return retnode; } // Creates a XmlWhitespace node. - public virtual XmlWhitespace CreateWhitespace(string text) + public virtual XmlWhitespace CreateWhitespace(string? text) { return new XmlWhitespace(text, this); } @@ -912,7 +918,7 @@ namespace System.Xml // Creates an XmlAttribute with the specified LocalName // and NamespaceURI. - public XmlAttribute CreateAttribute(string qualifiedName, string namespaceURI) + public XmlAttribute CreateAttribute(string qualifiedName, string? namespaceURI) { string prefix = string.Empty; string localName = string.Empty; @@ -923,7 +929,7 @@ namespace System.Xml // Creates an XmlElement with the specified LocalName and // NamespaceURI. - public XmlElement CreateElement(string qualifiedName, string namespaceURI) + public XmlElement CreateElement(string qualifiedName, string? namespaceURI) { string prefix = string.Empty; string localName = string.Empty; @@ -939,16 +945,16 @@ namespace System.Xml } // Returns the XmlElement with the specified ID. - public virtual XmlElement GetElementById(string elementId) + public virtual XmlElement? GetElementById(string elementId) { if (_htElementIdMap != null) { - ArrayList elementList = (ArrayList)(_htElementIdMap[elementId]); + ArrayList? elementList = (ArrayList?)(_htElementIdMap[elementId]); if (elementList != null) { foreach (WeakReference elemRef in elementList) { - XmlElement elem = (XmlElement)elemRef.Target; + XmlElement? elem = (XmlElement?)elemRef.Target; if (elem != null && elem.IsConnected()) return elem; @@ -966,14 +972,14 @@ namespace System.Xml private XmlNode ImportNodeInternal(XmlNode node, bool deep) { - XmlNode newNode = null; - if (node == null) { throw new InvalidOperationException(SR.Xdom_Import_NullNode); } else { + XmlNode newNode; + switch (node.NodeType) { case XmlNodeType.Element: @@ -996,7 +1002,7 @@ namespace System.Xml newNode = CreateComment(node.Value); break; case XmlNodeType.ProcessingInstruction: - newNode = CreateProcessingInstruction(node.Name, node.Value); + newNode = CreateProcessingInstruction(node.Name, node.Value!); break; case XmlNodeType.XmlDeclaration: XmlDeclaration decl = (XmlDeclaration)node; @@ -1032,25 +1038,25 @@ namespace System.Xml default: throw new InvalidOperationException(SR.Format(CultureInfo.InvariantCulture, SR.Xdom_Import, node.NodeType)); } - } - return newNode; + return newNode; + } } private void ImportAttributes(XmlNode fromElem, XmlNode toElem) { - int cAttr = fromElem.Attributes.Count; + int cAttr = fromElem.Attributes!.Count; for (int iAttr = 0; iAttr < cAttr; iAttr++) { if (fromElem.Attributes[iAttr].Specified) - toElem.Attributes.SetNamedItem(ImportNodeInternal(fromElem.Attributes[iAttr], true)); + toElem.Attributes!.SetNamedItem(ImportNodeInternal(fromElem.Attributes[iAttr], true)); } } private void ImportChildren(XmlNode fromNode, XmlNode toNode, bool deep) { Debug.Assert(toNode.NodeType != XmlNodeType.EntityReference); - for (XmlNode n = fromNode.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = fromNode.FirstChild; n != null; n = n.NextSibling) { toNode.AppendChild(ImportNodeInternal(n, deep)); } @@ -1067,17 +1073,17 @@ namespace System.Xml // Creates a XmlAttribute with the specified Prefix, LocalName, // and NamespaceURI. - public virtual XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI) + public virtual XmlAttribute CreateAttribute(string? prefix, string localName, string? namespaceURI) { return new XmlAttribute(AddAttrXmlName(prefix, localName, namespaceURI, null), this); } - protected internal virtual XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) + protected internal virtual XmlAttribute CreateDefaultAttribute(string? prefix, string localName, string? namespaceURI) { return new XmlUnspecifiedAttribute(prefix, localName, namespaceURI, this); } - public virtual XmlElement CreateElement(string prefix, string localName, string namespaceURI) + public virtual XmlElement CreateElement(string? prefix, string localName, string? namespaceURI) { XmlElement elem = new XmlElement(AddXmlName(prefix, localName, namespaceURI, null), true, this); if (!IsLoading) @@ -1123,7 +1129,7 @@ namespace System.Xml // Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI. - public virtual XmlNode CreateNode(XmlNodeType type, string prefix, string name, string namespaceURI) + public virtual XmlNode CreateNode(XmlNodeType type, string? prefix, string name, string? namespaceURI) { switch (type) { @@ -1179,23 +1185,23 @@ namespace System.Xml // Creates an XmlNode with the specified node type, Name, and // NamespaceURI. - public virtual XmlNode CreateNode(string nodeTypeString, string name, string namespaceURI) + public virtual XmlNode CreateNode(string nodeTypeString, string name, string? namespaceURI) { return CreateNode(ConvertToNodeType(nodeTypeString), name, namespaceURI); } // Creates an XmlNode with the specified XmlNodeType, Name, and // NamespaceURI. - public virtual XmlNode CreateNode(XmlNodeType type, string name, string namespaceURI) + public virtual XmlNode CreateNode(XmlNodeType type, string name, string? namespaceURI) { return CreateNode(type, null, name, namespaceURI); } // Creates an XmlNode object based on the information in the XmlReader. // The reader must be positioned on a node or attribute. - public virtual XmlNode ReadNode(XmlReader reader) + public virtual XmlNode? ReadNode(XmlReader reader) { - XmlNode node = null; + XmlNode? node = null; try { IsLoading = true; @@ -1206,6 +1212,7 @@ namespace System.Xml { IsLoading = false; } + return node; } @@ -1361,7 +1368,7 @@ namespace System.Xml } //TextEncoding is the one from XmlDeclaration if there is any - internal Encoding TextEncoding + internal Encoding? TextEncoding { get { @@ -1377,6 +1384,7 @@ namespace System.Xml } } + [AllowNull] public override string InnerText { set @@ -1445,14 +1453,14 @@ namespace System.Xml //that of textwriter's encoding public virtual void Save(XmlWriter w) { - XmlNode n = this.FirstChild; + XmlNode? n = this.FirstChild; if (n == null) return; if (w.WriteState == WriteState.Start) { if (n is XmlDeclaration) { - if (Standalone.Length == 0) + if (Standalone!.Length == 0) w.WriteStartDocument(); else if (Standalone == "yes") w.WriteStartDocument(true); @@ -1492,12 +1500,12 @@ namespace System.Xml } } - public void Validate(ValidationEventHandler validationEventHandler) + public void Validate(ValidationEventHandler? validationEventHandler) { Validate(validationEventHandler, this); } - public void Validate(ValidationEventHandler validationEventHandler, XmlNode nodeToValidate) + public void Validate(ValidationEventHandler? validationEventHandler, XmlNode nodeToValidate) { if (_schemas == null || _schemas.Count == 0) { //Should we error @@ -1592,7 +1600,7 @@ namespace System.Xml } } - internal override XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) + internal override XmlNodeChangedEventArgs? GetEventArgs(XmlNode node, XmlNode? oldParent, XmlNode? newParent, string? oldValue, string? newValue, XmlNodeChangedAction action) { _reportValidity = false; @@ -1620,13 +1628,13 @@ namespace System.Xml return new XmlNodeChangedEventArgs(node, oldParent, newParent, oldValue, newValue, action); } - internal XmlNodeChangedEventArgs GetInsertEventArgsForLoad(XmlNode node, XmlNode newParent) + internal XmlNodeChangedEventArgs? GetInsertEventArgsForLoad(XmlNode node, XmlNode newParent) { if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null) { return null; } - string nodeValue = node.Value; + string? nodeValue = node.Value; return new XmlNodeChangedEventArgs(node, null, newParent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); } @@ -1682,10 +1690,10 @@ namespace System.Xml // If so, return the newly created default attribute (with children tree); // Otherwise, return null. - internal XmlAttribute GetDefaultAttribute(XmlElement elem, string attrPrefix, string attrLocalname, string attrNamespaceURI) + internal XmlAttribute? GetDefaultAttribute(XmlElement elem, string attrPrefix, string attrLocalname, string attrNamespaceURI) { - SchemaInfo schInfo = DtdSchemaInfo; - SchemaElementDecl ed = GetSchemaElementDecl(elem); + SchemaInfo? schInfo = DtdSchemaInfo; + SchemaElementDecl? ed = GetSchemaElementDecl(elem); if (ed != null && ed.AttDefs != null) { foreach (KeyValuePair attrDefs in ed.AttDefs) @@ -1696,7 +1704,7 @@ namespace System.Xml { if (attdef.Name.Name == attrLocalname) { - if ((schInfo.SchemaType == SchemaType.DTD && attdef.Name.Namespace == attrPrefix) || + if ((schInfo!.SchemaType == SchemaType.DTD && attdef.Name.Namespace == attrPrefix) || (schInfo.SchemaType != SchemaType.DTD && attdef.Name.Namespace == attrNamespaceURI)) { //find a def attribute with the same name, build a default attribute and return @@ -1710,46 +1718,46 @@ namespace System.Xml return null; } - internal string Version + internal string? Version { get { - XmlDeclaration decl = Declaration; + XmlDeclaration? decl = Declaration; if (decl != null) return decl.Version; return null; } } - internal string Encoding + internal string? Encoding { get { - XmlDeclaration decl = Declaration; + XmlDeclaration? decl = Declaration; if (decl != null) return decl.Encoding; return null; } } - internal string Standalone + internal string? Standalone { get { - XmlDeclaration decl = Declaration; + XmlDeclaration? decl = Declaration; if (decl != null) return decl.Standalone; return null; } } - internal XmlEntity GetEntityNode(string name) + internal XmlEntity? GetEntityNode(string name) { if (DocumentType != null) { XmlNamedNodeMap entites = DocumentType.Entities; if (entites != null) - return (XmlEntity)(entites.GetNamedItem(name)); + return (XmlEntity?)(entites.GetNamedItem(name)); } return null; } @@ -1760,7 +1768,7 @@ namespace System.Xml { if (_reportValidity) { - XmlElement documentElement = DocumentElement; + XmlElement? documentElement = DocumentElement; if (documentElement != null) { switch (documentElement.SchemaInfo.Validity) @@ -1796,7 +1804,7 @@ namespace System.Xml if (!CanInsertAfter(newChild, LastChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); - XmlNodeChangedEventArgs args = GetInsertEventArgsForLoad(newChild, this); + XmlNodeChangedEventArgs? args = GetInsertEventArgsForLoad(newChild, this); if (args != null) BeforeEvent(args); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs index 9010ff1..ae03454 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; using System.Xml.XPath; @@ -43,25 +44,26 @@ namespace System.Xml // such as insertBefore() and appendChild(). public class XmlDocumentFragment : XmlNode { - private XmlLinkedNode _lastChild; + private XmlLinkedNode? _lastChild; protected internal XmlDocumentFragment(XmlDocument ownerDocument) : base() { if (ownerDocument == null) throw new ArgumentException(SR.Xdom_Node_Null_Doc); + parentNode = ownerDocument; } // Gets the name of the node. public override string Name { - get { return OwnerDocument.strDocumentFragmentName; } + get { return OwnerDocument!.strDocumentFragmentName; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { - get { return OwnerDocument.strDocumentFragmentName; } + get { return OwnerDocument!.strDocumentFragmentName; } } // Gets the type of the current node. @@ -71,7 +73,7 @@ namespace System.Xml } // Gets the parent of this node (for nodes that can have parents). - public override XmlNode ParentNode + public override XmlNode? ParentNode { get { return null; } } @@ -81,7 +83,7 @@ namespace System.Xml { get { - return (XmlDocument)parentNode; + return (XmlDocument)parentNode!; } } @@ -118,7 +120,7 @@ namespace System.Xml get { return true; } } - internal override XmlLinkedNode LastNode + internal override XmlLinkedNode? LastNode { get { return _lastChild; } set { _lastChild = value; } @@ -140,7 +142,7 @@ namespace System.Xml case XmlNodeType.XmlDeclaration: //if there is an XmlDeclaration node, it has to be the first node; - XmlNode firstNode = FirstChild; + XmlNode? firstNode = FirstChild; if (firstNode == null || firstNode.NodeType != XmlNodeType.XmlDeclaration) return true; else @@ -149,7 +151,7 @@ namespace System.Xml return false; } } - internal override bool CanInsertAfter(XmlNode newChild, XmlNode refChild) + internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) { Debug.Assert(newChild != null); //should be checked that newChild is not null before this function call if (newChild.NodeType == XmlNodeType.XmlDeclaration) @@ -165,7 +167,7 @@ namespace System.Xml return true; } - internal override bool CanInsertBefore(XmlNode newChild, XmlNode refChild) + internal override bool CanInsertBefore(XmlNode newChild, XmlNode? refChild) { Debug.Assert(newChild != null); //should be checked that newChild is not null before this function call if (newChild.NodeType == XmlNodeType.XmlDeclaration) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs index 9601322..ab166f9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; using System.Xml.Schema; @@ -10,17 +11,17 @@ namespace System.Xml public class XmlDocumentType : XmlLinkedNode { private readonly string _name; - private readonly string _publicId; - private readonly string _systemId; - private readonly string _internalSubset; + private readonly string? _publicId; + private readonly string? _systemId; + private readonly string? _internalSubset; private bool _namespaces; - private XmlNamedNodeMap _entities; - private XmlNamedNodeMap _notations; + private XmlNamedNodeMap? _entities; + private XmlNamedNodeMap? _notations; // parsed DTD - private SchemaInfo _schemaInfo; + private SchemaInfo? _schemaInfo; - protected internal XmlDocumentType(string name, string publicId, string systemId, string internalSubset, XmlDocument doc) : base(doc) + protected internal XmlDocumentType(string name, string? publicId, string? systemId, string? internalSubset, XmlDocument doc) : base(doc) { _name = name; _publicId = publicId; @@ -104,21 +105,21 @@ namespace System.Xml // // Gets the value of the public identifier on the DOCTYPE declaration. - public string PublicId + public string? PublicId { get { return _publicId; } } // Gets the value of // the system identifier on the DOCTYPE declaration. - public string SystemId + public string? SystemId { get { return _systemId; } } // Gets the entire value of the DTD internal subset // on the DOCTYPE declaration. - public string InternalSubset + public string? InternalSubset { get { return _internalSubset; } } @@ -141,7 +142,7 @@ namespace System.Xml // Intentionally do nothing } - internal SchemaInfo DtdSchemaInfo + internal SchemaInfo? DtdSchemaInfo { get { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDomTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDomTextWriter.cs index 72ebd83..9697b49 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDomTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDomTextWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.IO; using System.Text; @@ -11,11 +12,11 @@ namespace System.Xml // This is not possible with XmlTextWriter. But this class inherits XmlTextWriter. internal class XmlDOMTextWriter : XmlTextWriter { - public XmlDOMTextWriter(Stream w, Encoding encoding) : base(w, encoding) + public XmlDOMTextWriter(Stream w, Encoding? encoding) : base(w, encoding) { } - public XmlDOMTextWriter(string filename, Encoding encoding) : base(filename, encoding) + public XmlDOMTextWriter(string filename, Encoding? encoding) : base(filename, encoding) { } @@ -25,20 +26,20 @@ namespace System.Xml // Overrides the baseclass implementation so that emptystring prefixes do // do not fail if namespace is not specified. - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { - if ((ns.Length == 0) && (prefix.Length != 0)) - prefix = ""; + if (string.IsNullOrEmpty(ns) && !string.IsNullOrEmpty(prefix)) + prefix = string.Empty; base.WriteStartElement(prefix, localName, ns); } // Overrides the baseclass implementation so that emptystring prefixes do // do not fail if namespace is not specified. - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { - if ((ns.Length == 0) && (prefix.Length != 0)) - prefix = ""; + if (string.IsNullOrEmpty(ns) && !string.IsNullOrEmpty(prefix)) + prefix = string.Empty; base.WriteStartAttribute(prefix, localName, ns); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs index 9725057..1715d66 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; using System.Xml.XPath; @@ -14,8 +15,8 @@ namespace System.Xml public class XmlElement : XmlLinkedNode { private XmlName _name; - private XmlAttributeCollection _attributes; - private XmlLinkedNode _lastChild; // == this for empty elements otherwise it is the last child + private XmlAttributeCollection? _attributes; + private XmlLinkedNode? _lastChild; // == this for empty elements otherwise it is the last child internal XmlElement(XmlName name, bool empty, XmlDocument doc) : base(doc) { @@ -28,6 +29,7 @@ namespace System.Xml } if (name.LocalName.Length == 0) throw new ArgumentException(SR.Xdom_Empty_LocalName); + _name = name; if (empty) { @@ -35,7 +37,7 @@ namespace System.Xml } } - protected internal XmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc) + protected internal XmlElement(string prefix, string localName, string? namespaceURI, XmlDocument doc) : this(doc.AddXmlName(prefix, localName, namespaceURI, null), true, doc) { } @@ -63,7 +65,7 @@ namespace System.Xml foreach (XmlAttribute attr in Attributes) { XmlAttribute newAttr = (XmlAttribute)(attr.CloneNode(true)); - XmlUnspecifiedAttribute unspecAttr = newAttr as XmlUnspecifiedAttribute; + XmlUnspecifiedAttribute? unspecAttr = newAttr as XmlUnspecifiedAttribute; if (unspecAttr != null && attr.Specified == false) { unspecAttr.SetSpecified(false); @@ -71,6 +73,7 @@ namespace System.Xml element.Attributes.InternalAppendAttribute(newAttr); } } + if (deep) element.CopyChildren(doc, this, deep); @@ -108,7 +111,7 @@ namespace System.Xml get { return XmlNodeType.Element; } } - public override XmlNode ParentNode + public override XmlNode? ParentNode { get { @@ -133,7 +136,7 @@ namespace System.Xml //the function is provided only at Load time to speed up Load process internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { - XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this); + XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); @@ -198,13 +201,12 @@ namespace System.Xml } } - internal override XmlLinkedNode LastNode + internal override XmlLinkedNode? LastNode { get { return _lastChild == this ? null : _lastChild; } - set { _lastChild = value; @@ -267,9 +269,10 @@ namespace System.Xml // Returns the value for the attribute with the specified name. public virtual string GetAttribute(string name) { - XmlAttribute attr = GetAttributeNode(name); + XmlAttribute? attr = GetAttributeNode(name); if (attr != null) return attr.Value; + return string.Empty; } @@ -277,7 +280,7 @@ namespace System.Xml // with the specified name. public virtual void SetAttribute(string name, string value) { - XmlAttribute attr = GetAttributeNode(name); + XmlAttribute? attr = GetAttributeNode(name); if (attr == null) { attr = OwnerDocument.CreateAttribute(name); @@ -298,7 +301,7 @@ namespace System.Xml } // Returns the XmlAttribute with the specified name. - public virtual XmlAttribute GetAttributeNode(string name) + public virtual XmlAttribute? GetAttributeNode(string name) { if (HasAttributes) return Attributes[name]; @@ -310,14 +313,15 @@ namespace System.Xml { if (newAttr.OwnerElement != null) throw new InvalidOperationException(SR.Xdom_Attr_InUse); + return (XmlAttribute)Attributes.SetNamedItem(newAttr); } // Removes the specified XmlAttribute. - public virtual XmlAttribute RemoveAttributeNode(XmlAttribute oldAttr) + public virtual XmlAttribute? RemoveAttributeNode(XmlAttribute oldAttr) { if (HasAttributes) - return (XmlAttribute)Attributes.Remove(oldAttr); + return (XmlAttribute?)Attributes.Remove(oldAttr); return null; } @@ -333,19 +337,20 @@ namespace System.Xml // // Returns the value for the attribute with the specified LocalName and NamespaceURI. - public virtual string GetAttribute(string localName, string namespaceURI) + public virtual string GetAttribute(string localName, string? namespaceURI) { - XmlAttribute attr = GetAttributeNode(localName, namespaceURI); + XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr != null) return attr.Value; + return string.Empty; } // Sets the value of the attribute with the specified name // and namespace. - public virtual string SetAttribute(string localName, string namespaceURI, string value) + public virtual string SetAttribute(string localName, string? namespaceURI, string value) { - XmlAttribute attr = GetAttributeNode(localName, namespaceURI); + XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr == null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); @@ -361,13 +366,13 @@ namespace System.Xml } // Removes an attribute specified by LocalName and NamespaceURI. - public virtual void RemoveAttribute(string localName, string namespaceURI) + public virtual void RemoveAttribute(string localName, string? namespaceURI) { RemoveAttributeNode(localName, namespaceURI); } // Returns the XmlAttribute with the specified LocalName and NamespaceURI. - public virtual XmlAttribute GetAttributeNode(string localName, string namespaceURI) + public virtual XmlAttribute? GetAttributeNode(string localName, string? namespaceURI) { if (HasAttributes) return Attributes[localName, namespaceURI]; @@ -375,26 +380,28 @@ namespace System.Xml } // Adds the specified XmlAttribute. - public virtual XmlAttribute SetAttributeNode(string localName, string namespaceURI) + public virtual XmlAttribute SetAttributeNode(string localName, string? namespaceURI) { - XmlAttribute attr = GetAttributeNode(localName, namespaceURI); + XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr == null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); Attributes.InternalAppendAttribute(attr); } + return attr; } // Removes the XmlAttribute specified by LocalName and NamespaceURI. - public virtual XmlAttribute RemoveAttributeNode(string localName, string namespaceURI) + public virtual XmlAttribute? RemoveAttributeNode(string localName, string? namespaceURI) { if (HasAttributes) { - XmlAttribute attr = GetAttributeNode(localName, namespaceURI); + XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); Attributes.Remove(attr); return attr; } + return null; } @@ -413,7 +420,7 @@ namespace System.Xml // Determines whether the current node has the specified // attribute from the specified namespace. - public virtual bool HasAttribute(string localName, string namespaceURI) + public virtual bool HasAttribute(string localName, string? namespaceURI) { return GetAttributeNode(localName, namespaceURI) != null; } @@ -444,10 +451,11 @@ namespace System.Xml } // This method is copied from System.Xml.Linq.ElementWriter.WriteElement but adapted to DOM - private static void WriteElementTo(XmlWriter writer, XmlElement e) + private static void WriteElementTo(XmlWriter writer, XmlElement el) { + XmlElement? e = el; XmlNode root = e; - XmlNode n = e; + XmlNode? n = e; while (true) { e = n as XmlElement; @@ -480,15 +488,18 @@ namespace System.Xml // Use virtual dispatch (might recurse) n.WriteTo(writer); } + // Go back to the parent after writing the last child - while (n != root && n == n.ParentNode.LastChild) + while (n != root && n == n.ParentNode!.LastChild) { n = n.ParentNode; Debug.Assert(n != null); writer.WriteFullEndElement(); } + if (n == root) break; + n = n.NextSibling; Debug.Assert(n != null); } @@ -513,17 +524,18 @@ namespace System.Xml // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { - for (XmlNode node = FirstChild; node != null; node = node.NextSibling) + for (XmlNode? node = FirstChild; node != null; node = node.NextSibling) { node.WriteTo(w); } } // Removes the attribute node with the specified index from the attribute collection. - public virtual XmlNode RemoveAttributeAt(int i) + public virtual XmlNode? RemoveAttributeAt(int i) { if (HasAttributes) - return _attributes.RemoveAt(i); + return _attributes!.RemoveAt(i); + return null; } @@ -532,7 +544,7 @@ namespace System.Xml { if (HasAttributes) { - _attributes.RemoveAll(); + _attributes!.RemoveAll(); } } @@ -585,7 +597,7 @@ namespace System.Xml } set { - XmlLinkedNode linkedNode = LastNode; + XmlLinkedNode? linkedNode = LastNode; if (linkedNode != null && //there is one child linkedNode.NodeType == XmlNodeType.Text && //which is text node linkedNode.next == linkedNode) // and it is the only child @@ -601,18 +613,19 @@ namespace System.Xml } } - public override XmlNode NextSibling + public override XmlNode? NextSibling { get { if (this.parentNode != null && this.parentNode.LastNode != this) return next; + return null; } } - internal override void SetParent(XmlNode node) + internal override void SetParent(XmlNode? node) { this.parentNode = node; } @@ -621,13 +634,15 @@ namespace System.Xml internal override string XPLocalName { get { return LocalName; } } - internal override string GetXPAttribute(string localName, string ns) + internal override string? GetXPAttribute(string localName, string ns) { if (ns == OwnerDocument.strReservedXmlns) return null; - XmlAttribute attr = GetAttributeNode(localName, ns); + + XmlAttribute? attr = GetAttributeNode(localName, ns); if (attr != null) return attr.Value; + return string.Empty; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs index 3892576..02211d6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; using System.Diagnostics; @@ -8,12 +9,12 @@ namespace System.Xml { internal class XmlElementList : XmlNodeList { - private readonly string _asterisk; + private readonly string _asterisk = null!; private int _changeCount; //recording the total number that the dom tree has been changed ( insertion and deletion ) //the member vars below are saved for further reconstruction - private readonly string _name; //only one of 2 string groups will be initialized depends on which constructor is called. - private string _localName; - private string _namespaceURI; + private readonly string? _name; //only one of 2 string groups will be initialized depends on which constructor is called. + private string? _localName; + private string? _namespaceURI; private readonly XmlNode _rootNode; // the member vars below serves the optimization of accessing of the elements in the list private int _curInd; // -1 means the starting point for a new search round @@ -22,7 +23,7 @@ namespace System.Xml private bool _atomized; //whether the localname and namespaceuri are atomized private int _matchCount; // cached list count. -1 means it needs reconstruction - private WeakReference _listener; // XmlElementListListener + private WeakReference? _listener; // XmlElementListListener private XmlElementList(XmlNode parent) { @@ -50,11 +51,12 @@ namespace System.Xml if (_atomized == false) { XmlNameTable nameTable = _rootNode.Document.NameTable; - _localName = nameTable.Add(_localName); - _namespaceURI = nameTable.Add(_namespaceURI); + _localName = nameTable.Add(_localName!); + _namespaceURI = nameTable.Add(_namespaceURI!); _atomized = true; } - if (IsMatch(args.Node)) + + if (IsMatch(args.Node!)) { _changeCount++; _curInd = -1; @@ -62,6 +64,7 @@ namespace System.Xml if (args.Action == XmlNodeChangedAction.Insert) _empty = false; } + _matchCount = -1; } @@ -91,6 +94,7 @@ namespace System.Xml _localName = localName; _namespaceURI = namespaceURI; } + _name = null; } @@ -100,11 +104,11 @@ namespace System.Xml } // return the next element node that is in PreOrder - private XmlNode NextElemInPreOrder(XmlNode curNode) + private XmlNode? NextElemInPreOrder(XmlNode curNode) { Debug.Assert(curNode != null); //For preorder walking, first try its child - XmlNode retNode = curNode.FirstChild; + XmlNode? retNode = curNode.FirstChild; if (retNode == null) { //if no child, the next node forward will the be the NextSibling of the first ancestor which has NextSibling @@ -127,11 +131,11 @@ namespace System.Xml } // return the previous element node that is in PreOrder - private XmlNode PrevElemInPreOrder(XmlNode curNode) + private XmlNode? PrevElemInPreOrder(XmlNode curNode) { Debug.Assert(curNode != null); //For preorder walking, the previous node will be the right-most node in the tree of PreviousSibling of the curNode - XmlNode retNode = curNode.PreviousSibling; + XmlNode? retNode = curNode.PreviousSibling; // so if the PreviousSibling is not null, going through the tree down to find the right-most node while (retNode != null) { @@ -172,10 +176,10 @@ namespace System.Xml return false; } - private XmlNode GetMatchingNode(XmlNode n, bool bNext) + private XmlNode? GetMatchingNode(XmlNode n, bool bNext) { Debug.Assert(n != null); - XmlNode node = n; + XmlNode? node = n; do { if (bNext) @@ -186,21 +190,22 @@ namespace System.Xml return node; } - private XmlNode GetNthMatchingNode(XmlNode n, bool bNext, int nCount) + private XmlNode? GetNthMatchingNode(XmlNode n, bool bNext, int nCount) { Debug.Assert(n != null); - XmlNode node = n; + XmlNode? node = n; for (int ind = 0; ind < nCount; ind++) { node = GetMatchingNode(node, bNext); if (node == null) return null; } + return node; } //the function is for the enumerator to find out the next available matching element node - public XmlNode GetNextNode(XmlNode n) + public XmlNode? GetNextNode(XmlNode? n) { if (_empty == true) return null; @@ -208,7 +213,7 @@ namespace System.Xml return GetMatchingNode(node, true); } - public override XmlNode Item(int index) + public override XmlNode? Item(int index) { if (_rootNode == null || index < 0) return null; @@ -221,13 +226,15 @@ namespace System.Xml bool bForward = (nDiff > 0); if (nDiff < 0) nDiff = -nDiff; - XmlNode node; + + XmlNode? node; if ((node = GetNthMatchingNode(_curElem, bForward, nDiff)) != null) { _curInd = index; _curElem = node; return _curElem; } + return null; } @@ -237,21 +244,25 @@ namespace System.Xml { if (_empty == true) return 0; + if (_matchCount < 0) { int currMatchCount = 0; int currChangeCount = _changeCount; - XmlNode node = _rootNode; + XmlNode? node = _rootNode; while ((node = GetMatchingNode(node, true)) != null) { currMatchCount++; } + if (currChangeCount != _changeCount) { return currMatchCount; } + _matchCount = currMatchCount; } + return _matchCount; } } @@ -259,7 +270,8 @@ namespace System.Xml public override IEnumerator GetEnumerator() { if (_empty == true) - return new XmlEmptyElementListEnumerator(this); ; + return new XmlEmptyElementListEnumerator(this); + return new XmlElementListEnumerator(this); } @@ -273,11 +285,12 @@ namespace System.Xml { if (_listener != null) { - XmlElementListListener listener = (XmlElementListListener)_listener.Target; + XmlElementListListener? listener = (XmlElementListListener?)_listener.Target; if (listener != null) { listener.Unregister(); } + _listener = null; } } @@ -286,7 +299,7 @@ namespace System.Xml internal class XmlElementListEnumerator : IEnumerator { private readonly XmlElementList _list; - private XmlNode _curElem; + private XmlNode? _curElem; private int _changeCount; //save the total number that the dom tree has been changed ( insertion and deletion ) when this enumerator is created public XmlElementListEnumerator(XmlElementList list) @@ -317,7 +330,7 @@ namespace System.Xml _changeCount = _list.ChangeCount; } - public object Current + public object? Current { get { return _curElem; } } @@ -338,7 +351,7 @@ namespace System.Xml { } - public object Current + public object? Current { get { return null; } } @@ -346,7 +359,7 @@ namespace System.Xml internal class XmlElementListListener { - private WeakReference _elemList; + private WeakReference? _elemList; private readonly XmlDocument _doc; private readonly XmlNodeChangedEventHandler _nodeChangeHandler; @@ -365,7 +378,7 @@ namespace System.Xml { if (_elemList != null) { - XmlElementList el = (XmlElementList)_elemList.Target; + XmlElementList? el = (XmlElementList?)_elemList.Target; if (null != el) { el.ConcurrencyCheck(args); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs index cc8523f..636bae9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs @@ -1,20 +1,21 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { // Represents a parsed or unparsed entity in the XML document. public class XmlEntity : XmlNode { - private readonly string _publicId; - private readonly string _systemId; - private readonly string _notationName; + private readonly string? _publicId; + private readonly string? _systemId; + private readonly string? _notationName; private readonly string _name; - private string _baseURI; - private XmlLinkedNode _lastChild; + private string _baseURI = string.Empty; + private XmlLinkedNode? _lastChild; private bool _childrenFoliating; - internal XmlEntity(string name, string strdata, string publicId, string systemId, string notationName, XmlDocument doc) : base(doc) + internal XmlEntity(string name, string? strdata, string? publicId, string? systemId, string? notationName, XmlDocument doc) : base(doc) { _name = doc.NameTable.Add(name); _publicId = publicId; @@ -71,7 +72,7 @@ namespace System.Xml get { return true; } } - internal override XmlLinkedNode LastNode + internal override XmlLinkedNode? LastNode { get { @@ -106,20 +107,20 @@ namespace System.Xml } // Gets the value of the public identifier on the entity declaration. - public string PublicId + public string? PublicId { get { return _publicId; } } // Gets the value of the system identifier on the entity declaration. - public string SystemId + public string? SystemId { get { return _systemId; } } // Gets the name of the optional NDATA attribute on the // entity declaration. - public string NotationName + public string? NotationName { get { return _notationName; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs index 0d73a24..59d7c59 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; namespace System.Xml @@ -30,7 +31,7 @@ namespace System.Xml public class XmlEntityReference : XmlLinkedNode { private readonly string _name; - private XmlLinkedNode _lastChild; + private XmlLinkedNode? _lastChild; protected internal XmlEntityReference(string name, XmlDocument doc) : base(doc) { @@ -41,6 +42,7 @@ namespace System.Xml throw new ArgumentException(SR.Xdom_InvalidCharacter_EntityReference); } } + _name = doc.NameTable.Add(name); doc.fEntRefNodesPresent = true; } @@ -58,7 +60,7 @@ namespace System.Xml } // Gets or sets the value of the node. - public override string Value + public override string? Value { get { @@ -103,7 +105,7 @@ namespace System.Xml get { return true; } } - internal override void SetParent(XmlNode node) + internal override void SetParent(XmlNode? node) { base.SetParent(node); if (LastNode == null && node != null && node != OwnerDocument) @@ -119,7 +121,7 @@ namespace System.Xml this.SetParent(node); } - internal override XmlLinkedNode LastNode + internal override XmlLinkedNode? LastNode { get { @@ -174,7 +176,7 @@ namespace System.Xml { get { - return OwnerDocument.BaseURI; + return OwnerDocument!.BaseURI; } } @@ -197,7 +199,7 @@ namespace System.Xml get { //get the associate entity and return its baseUri - XmlEntity ent = OwnerDocument.GetEntityNode(_name); + XmlEntity? ent = OwnerDocument!.GetEntityNode(_name); if (ent != null) { if (!string.IsNullOrEmpty(ent.SystemId)) @@ -205,6 +207,7 @@ namespace System.Xml else return ent.BaseURI; } + return string.Empty; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEventChangedAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEventChangedAction.cs index 1cf0a0c..59c2540 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEventChangedAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEventChangedAction.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { // Specifies the type of node change diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs index 395c4ef..5dfbecc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { // Provides methods for performing operations that are independent of any diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs index 7a88926..41ae463 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs @@ -1,12 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { // Gets the node immediately preceding or following this node. public abstract class XmlLinkedNode : XmlNode { - internal XmlLinkedNode next; + internal XmlLinkedNode? next; internal XmlLinkedNode(XmlDocument doc) : base(doc) { @@ -14,40 +15,44 @@ namespace System.Xml } // Gets the node immediately preceding this node. - public override XmlNode PreviousSibling + public override XmlNode? PreviousSibling { get { - XmlNode parent = ParentNode; + XmlNode? parent = ParentNode; if (parent != null) { - XmlNode node = parent.FirstChild; + XmlNode? node = parent.FirstChild; while (node != null) { - XmlNode nextSibling = node.NextSibling; + XmlNode? nextSibling = node.NextSibling; if (nextSibling == this) { break; } + node = nextSibling; } + return node; } + return null; } } // Gets the node immediately following this node. - public override XmlNode NextSibling + public override XmlNode? NextSibling { get { - XmlNode parent = ParentNode; + XmlNode? parent = ParentNode; if (parent != null) { if (next != parent.FirstChild) return next; } + return null; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs index 71191dd..05e2848 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.IO; using System.Diagnostics; using System.Globalization; @@ -12,11 +13,10 @@ namespace System.Xml { internal class XmlLoader { - private XmlDocument _doc; - private XmlReader _reader; + private XmlDocument? _doc; + private XmlReader? _reader; private bool _preserveWhitespace; - public XmlLoader() { } @@ -38,7 +38,7 @@ namespace System.Xml throw new ArgumentException(SR.Xdom_Load_NoDocument); if (reader == null) throw new ArgumentException(SR.Xdom_Load_NoReader); - doc.SetBaseURI(reader.BaseURI); + doc.SetBaseURI(reader.BaseURI!); if (reader.Settings != null && reader.Settings.ValidationType == ValidationType.Schema) { @@ -57,7 +57,7 @@ namespace System.Xml { Debug.Assert(_reader != null); Debug.Assert(parentDoc != null); - XmlNode node = null; + XmlNode? node = null; while ((node = LoadNode(true)) != null) { parentDoc.AppendChildForLoad(node, parentDoc); @@ -66,7 +66,7 @@ namespace System.Xml } } - internal XmlNode ReadCurrentNode(XmlDocument doc, XmlReader reader) + internal XmlNode? ReadCurrentNode(XmlDocument doc, XmlReader reader) { _doc = doc; _reader = reader; @@ -83,7 +83,7 @@ namespace System.Xml } if (reader.ReadState == ReadState.Interactive) { - XmlNode n = LoadNode(true); + XmlNode n = LoadNode(true)!; // Move to the next node if (n.NodeType != XmlNodeType.Attribute) @@ -91,23 +91,24 @@ namespace System.Xml return n; } + return null; } - private XmlNode LoadNode(bool skipOverWhitespace) + private XmlNode? LoadNode(bool skipOverWhitespace) { - XmlReader r = _reader; - XmlNode parent = null; - XmlElement element; - IXmlSchemaInfo schemaInfo; + XmlReader r = _reader!; + XmlNode? parent = null; + XmlElement? element; + IXmlSchemaInfo? schemaInfo; do { - XmlNode node = null; + XmlNode? node = null; switch (r.NodeType) { case XmlNodeType.Element: bool fEmptyElement = r.IsEmptyElement; - element = _doc.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); + element = _doc!.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); element.IsEmpty = fEmptyElement; if (r.MoveToFirstAttribute()) @@ -155,7 +156,7 @@ namespace System.Xml element = parent as XmlElement; if (element != null) { - element.XmlName = _doc.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo); + element.XmlName = _doc!.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo); } } if (parent.ParentNode == null) @@ -178,17 +179,17 @@ namespace System.Xml break; case XmlNodeType.Text: - node = _doc.CreateTextNode(r.Value); + node = _doc!.CreateTextNode(r.Value); break; case XmlNodeType.SignificantWhitespace: - node = _doc.CreateSignificantWhitespace(r.Value); + node = _doc!.CreateSignificantWhitespace(r.Value); break; case XmlNodeType.Whitespace: if (_preserveWhitespace) { - node = _doc.CreateWhitespace(r.Value); + node = _doc!.CreateWhitespace(r.Value); break; } else if (parent == null && !skipOverWhitespace) @@ -201,7 +202,7 @@ namespace System.Xml continue; } case XmlNodeType.CDATA: - node = _doc.CreateCDataSection(r.Value); + node = _doc!.CreateCDataSection(r.Value); break; @@ -210,11 +211,11 @@ namespace System.Xml break; case XmlNodeType.ProcessingInstruction: - node = _doc.CreateProcessingInstruction(r.Name, r.Value); + node = _doc!.CreateProcessingInstruction(r.Name, r.Value); break; case XmlNodeType.Comment: - node = _doc.CreateComment(r.Value); + node = _doc!.CreateComment(r.Value); break; case XmlNodeType.DocumentType: @@ -228,7 +229,7 @@ namespace System.Xml Debug.Assert(node != null); if (parent != null) { - parent.AppendChildForLoad(node, _doc); + parent.AppendChildForLoad(node, _doc!); } else { @@ -245,12 +246,13 @@ namespace System.Xml parent = parent.ParentNode; } } + return parent; } private XmlAttribute LoadAttributeNode() { - Debug.Assert(_reader.NodeType == XmlNodeType.Attribute); + Debug.Assert(_reader!.NodeType == XmlNodeType.Attribute); XmlReader r = _reader; if (r.IsDefault) @@ -258,12 +260,13 @@ namespace System.Xml return LoadDefaultAttribute(); } - XmlAttribute attr = _doc.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI); - IXmlSchemaInfo schemaInfo = r.SchemaInfo; + XmlAttribute attr = _doc!.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI); + IXmlSchemaInfo? schemaInfo = r.SchemaInfo; if (schemaInfo != null) { attr.XmlName = _doc.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, schemaInfo); } + while (r.ReadAttributeValue()) { XmlNode node; @@ -289,6 +292,7 @@ namespace System.Xml default: throw UnexpectedNodeType(r.NodeType); } + Debug.Assert(node != null); attr.AppendChildForLoad(node, _doc); } @@ -298,11 +302,11 @@ namespace System.Xml private XmlAttribute LoadDefaultAttribute() { - Debug.Assert(_reader.IsDefault); + Debug.Assert(_reader!.IsDefault); XmlReader r = _reader; - XmlAttribute attr = _doc.CreateDefaultAttribute(r.Prefix, r.LocalName, r.NamespaceURI); - IXmlSchemaInfo schemaInfo = r.SchemaInfo; + XmlAttribute attr = _doc!.CreateDefaultAttribute(r.Prefix, r.LocalName, r.NamespaceURI); + IXmlSchemaInfo? schemaInfo = r.SchemaInfo; if (schemaInfo != null) { attr.XmlName = _doc.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, schemaInfo); @@ -310,7 +314,7 @@ namespace System.Xml LoadAttributeValue(attr, false); - XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute; + XmlUnspecifiedAttribute? defAttr = attr as XmlUnspecifiedAttribute; // If user overrides CreateDefaultAttribute, then attr will NOT be a XmlUnspecifiedAttribute instance. if (defAttr != null) defAttr.SetSpecified(false); @@ -320,19 +324,19 @@ namespace System.Xml private void LoadAttributeValue(XmlNode parent, bool direct) { - XmlReader r = _reader; + XmlReader r = _reader!; while (r.ReadAttributeValue()) { XmlNode node; switch (r.NodeType) { case XmlNodeType.Text: - node = direct ? new XmlText(r.Value, _doc) : _doc.CreateTextNode(r.Value); + node = direct ? new XmlText(r.Value, _doc!) : _doc!.CreateTextNode(r.Value); break; case XmlNodeType.EndEntity: return; case XmlNodeType.EntityReference: - node = direct ? new XmlEntityReference(_reader.LocalName, _doc) : _doc.CreateEntityReference(_reader.LocalName); + node = direct ? new XmlEntityReference(_reader!.LocalName, _doc!) : _doc!.CreateEntityReference(_reader!.LocalName); if (r.CanResolveEntity) { r.ResolveEntity(); @@ -341,7 +345,7 @@ namespace System.Xml // if the reader does not present any children for the ent-ref if (node.FirstChild == null) { - node.AppendChildForLoad(direct ? new XmlText(string.Empty) : _doc.CreateTextNode(string.Empty), _doc); + node.AppendChildForLoad(direct ? new XmlText(string.Empty) : _doc!.CreateTextNode(string.Empty), _doc!); } } break; @@ -349,42 +353,42 @@ namespace System.Xml throw UnexpectedNodeType(r.NodeType); } Debug.Assert(node != null); - parent.AppendChildForLoad(node, _doc); + parent.AppendChildForLoad(node, _doc!); } return; } private XmlEntityReference LoadEntityReferenceNode(bool direct) { - Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference); - XmlEntityReference eref = direct ? new XmlEntityReference(_reader.Name, _doc) : _doc.CreateEntityReference(_reader.Name); + Debug.Assert(_reader!.NodeType == XmlNodeType.EntityReference); + XmlEntityReference eref = direct ? new XmlEntityReference(_reader.Name, _doc!) : _doc!.CreateEntityReference(_reader.Name); if (_reader.CanResolveEntity) { _reader.ResolveEntity(); while (_reader.Read() && _reader.NodeType != XmlNodeType.EndEntity) { - XmlNode node = direct ? LoadNodeDirect() : LoadNode(false); + XmlNode? node = direct ? LoadNodeDirect() : LoadNode(false); if (node != null) { - eref.AppendChildForLoad(node, _doc); + eref.AppendChildForLoad(node, _doc!); } } // Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true, // if the reader does not present any children for the ent-ref if (eref.LastChild == null) - eref.AppendChildForLoad(_doc.CreateTextNode(string.Empty), _doc); + eref.AppendChildForLoad(_doc!.CreateTextNode(string.Empty), _doc); } return eref; } private XmlDeclaration LoadDeclarationNode() { - Debug.Assert(_reader.NodeType == XmlNodeType.XmlDeclaration); + Debug.Assert(_reader!.NodeType == XmlNodeType.XmlDeclaration); //parse data - string version = null; - string encoding = null; - string standalone = null; + string? version = null; + string? encoding = null; + string? standalone = null; // Try first to use the reader to get the xml decl "attributes". Since not all readers are required to support this, it is possible to have // implementations that do nothing @@ -412,15 +416,15 @@ namespace System.Xml if (version == null) ParseXmlDeclarationValue(_reader.Value, out version, out encoding, out standalone); - return _doc.CreateXmlDeclaration(version, encoding, standalone); + return _doc!.CreateXmlDeclaration(version!, encoding, standalone); } private XmlDocumentType LoadDocumentTypeNode() { - Debug.Assert(_reader.NodeType == XmlNodeType.DocumentType); + Debug.Assert(_reader!.NodeType == XmlNodeType.DocumentType); - string publicId = null; - string systemId = null; + string? publicId = null; + string? systemId = null; string internalSubset = _reader.Value; string localName = _reader.LocalName; while (_reader.MoveToNextAttribute()) @@ -436,9 +440,9 @@ namespace System.Xml } } - XmlDocumentType dtNode = _doc.CreateDocumentType(localName, publicId, systemId, internalSubset); + XmlDocumentType dtNode = _doc!.CreateDocumentType(localName, publicId, systemId, internalSubset); - IDtdInfo dtdInfo = _reader.DtdInfo; + IDtdInfo? dtdInfo = _reader.DtdInfo; if (dtdInfo != null) LoadDocumentType(dtdInfo, dtNode); else @@ -454,18 +458,18 @@ namespace System.Xml // because we do not want to let users extend these (if we would allow this, XmlDataDocument would have a problem, because // they do not know that those nodes should not be mapped). It can be also used for an optimized load path when if the // XmlDocument is not extended if XmlDocumentType and XmlDeclaration handling is added. - private XmlNode LoadNodeDirect() + private XmlNode? LoadNodeDirect() { - XmlReader r = _reader; - XmlNode parent = null; + XmlReader r = _reader!; + XmlNode? parent = null; do { - XmlNode node = null; + XmlNode? node = null; switch (r.NodeType) { case XmlNodeType.Element: - bool fEmptyElement = _reader.IsEmptyElement; - XmlElement element = new XmlElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _doc); + bool fEmptyElement = _reader!.IsEmptyElement; + XmlElement element = new XmlElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _doc!); element.IsEmpty = fEmptyElement; if (_reader.MoveToFirstAttribute()) @@ -481,7 +485,7 @@ namespace System.Xml // recursively load all children. if (!fEmptyElement) { - parent.AppendChildForLoad(element, _doc); + parent!.AppendChildForLoad(element, _doc!); parent = element; continue; } @@ -492,11 +496,12 @@ namespace System.Xml } case XmlNodeType.EndElement: - Debug.Assert(parent.NodeType == XmlNodeType.Element); + Debug.Assert(parent!.NodeType == XmlNodeType.Element); if (parent.ParentNode == null) { return parent; } + parent = parent.ParentNode; continue; @@ -512,13 +517,13 @@ namespace System.Xml break; case XmlNodeType.SignificantWhitespace: - node = new XmlSignificantWhitespace(_reader.Value, _doc); + node = new XmlSignificantWhitespace(_reader!.Value, _doc!); break; case XmlNodeType.Whitespace: if (_preserveWhitespace) { - node = new XmlWhitespace(_reader.Value, _doc); + node = new XmlWhitespace(_reader!.Value, _doc!); } else { @@ -527,29 +532,29 @@ namespace System.Xml break; case XmlNodeType.Text: - node = new XmlText(_reader.Value, _doc); + node = new XmlText(_reader!.Value, _doc!); break; case XmlNodeType.CDATA: - node = new XmlCDataSection(_reader.Value, _doc); + node = new XmlCDataSection(_reader!.Value, _doc!); break; case XmlNodeType.ProcessingInstruction: - node = new XmlProcessingInstruction(_reader.Name, _reader.Value, _doc); + node = new XmlProcessingInstruction(_reader!.Name, _reader.Value, _doc!); break; case XmlNodeType.Comment: - node = new XmlComment(_reader.Value, _doc); + node = new XmlComment(_reader!.Value, _doc!); break; default: - throw UnexpectedNodeType(_reader.NodeType); + throw UnexpectedNodeType(_reader!.NodeType); } Debug.Assert(node != null); if (parent != null) { - parent.AppendChildForLoad(node, _doc); + parent.AppendChildForLoad(node, _doc!); } else { @@ -563,18 +568,18 @@ namespace System.Xml private XmlAttribute LoadAttributeNodeDirect() { - XmlReader r = _reader; + XmlReader r = _reader!; XmlAttribute attr; if (r.IsDefault) { - XmlUnspecifiedAttribute defattr = new XmlUnspecifiedAttribute(r.Prefix, r.LocalName, r.NamespaceURI, _doc); + XmlUnspecifiedAttribute defattr = new XmlUnspecifiedAttribute(r.Prefix, r.LocalName, r.NamespaceURI, _doc!); LoadAttributeValue(defattr, true); defattr.SetSpecified(false); return defattr; } else { - attr = new XmlAttribute(r.Prefix, r.LocalName, r.NamespaceURI, _doc); + attr = new XmlAttribute(r.Prefix, r.LocalName, r.NamespaceURI, _doc!); LoadAttributeValue(attr, true); return attr; } @@ -582,7 +587,7 @@ namespace System.Xml internal void ParseDocumentType(XmlDocumentType dtNode) { - XmlDocument doc = dtNode.OwnerDocument; + XmlDocument doc = dtNode.OwnerDocument!; //if xmlresolver is set on doc, use that one, otherwise use the default one being created by xmlvalidatingreader if (doc.HasSetResolver) ParseDocumentType(dtNode, true, doc.GetResolver()); @@ -590,10 +595,10 @@ namespace System.Xml ParseDocumentType(dtNode, false, null); } - private void ParseDocumentType(XmlDocumentType dtNode, bool bUseResolver, XmlResolver resolver) + private void ParseDocumentType(XmlDocumentType dtNode, bool bUseResolver, XmlResolver? resolver) { _doc = dtNode.OwnerDocument; - XmlParserContext pc = new XmlParserContext(null, new XmlNamespaceManager(_doc.NameTable), null, null, null, null, _doc.BaseURI, string.Empty, XmlSpace.None); + XmlParserContext pc = new XmlParserContext(null, new XmlNamespaceManager(_doc!.NameTable), null, null, null, null, _doc.BaseURI, string.Empty, XmlSpace.None); XmlTextReaderImpl tr = new XmlTextReaderImpl("", XmlNodeType.Element, pc); tr.Namespaces = dtNode.ParseWithNamespaces; if (bUseResolver) @@ -610,7 +615,7 @@ namespace System.Xml private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode) { - SchemaInfo schInfo = dtdInfo as SchemaInfo; + SchemaInfo? schInfo = dtdInfo as SchemaInfo; if (schInfo == null) { throw new XmlException(SR.Xml_InternalError, string.Empty); @@ -620,7 +625,7 @@ namespace System.Xml if (schInfo != null) { //set the schema information into the document - _doc.DtdSchemaInfo = schInfo; + _doc!.DtdSchemaInfo = schInfo; // Notation hashtable if (schInfo.Notations != null) @@ -677,11 +682,11 @@ namespace System.Xml } #pragma warning restore 618 - private XmlParserContext GetContext(XmlNode node) + private XmlParserContext GetContext(XmlNode? node) { - string lang = null; + string? lang = null; XmlSpace spaceMode = XmlSpace.None; - XmlDocumentType docType = _doc.DocumentType; + XmlDocumentType? docType = _doc!.DocumentType; string baseURI = _doc.BaseURI; //constructing xmlnamespace HashSet prefixes = new HashSet(); @@ -692,7 +697,7 @@ namespace System.Xml // Process all xmlns, xmlns:prefix, xml:space and xml:lang attributes while (node != null && node != _doc) { - XmlElement element = node as XmlElement; + XmlElement? element = node as XmlElement; if (element != null && element.HasAttributes) { mgr.PushScope(); @@ -725,6 +730,7 @@ namespace System.Xml } } } + node = node.ParentNode; } return new XmlParserContext( @@ -758,7 +764,7 @@ namespace System.Xml if (nt == XmlNodeType.Entity) { - XmlNode node = null; + XmlNode? node = null; while (_reader.Read() && (node = LoadNodeDirect()) != null) { parentNode.AppendChildForLoad(node, _doc); @@ -766,19 +772,21 @@ namespace System.Xml } else { - XmlNode node = null; + XmlNode? node = null; while (_reader.Read() && (node = LoadNode(true)) != null) { parentNode.AppendChildForLoad(node, _doc); } } + _doc.IsLoading = bOrigLoading; } finally { _reader.Close(); } - return pc.NamespaceManager; + + return pc.NamespaceManager!; } internal void LoadInnerXmlElement(XmlElement node, string innerxmltext) @@ -807,9 +815,9 @@ namespace System.Xml for (int i = cAttrs - 1; i >= 0; --i) { XmlAttribute attr = attrs[i]; - if (attr.Prefix == _doc.strXmlns) + if (attr.Prefix == _doc!.strXmlns) { - string nsUri = mgr.LookupNamespace(attr.LocalName); + string? nsUri = mgr.LookupNamespace(attr.LocalName); if (nsUri != null) { if (attr.Value == nsUri) @@ -844,14 +852,15 @@ namespace System.Xml } } //now recursively remove the duplicate attributes on the children - XmlNode child = elem.FirstChild; + XmlNode? child = elem.FirstChild; while (child != null) { - XmlElement childElem = child as XmlElement; + XmlElement? childElem = child as XmlElement; if (childElem != null) RemoveDuplicateNamespace(childElem, mgr, true); child = child.NextSibling; } + mgr.PopScope(); } @@ -871,7 +880,7 @@ namespace System.Xml { //when the ent ref is not associated w/ an entity, append an empty string text node as child _doc = eref.OwnerDocument; - bool bOrigLoadingState = _doc.IsLoading; + bool bOrigLoadingState = _doc!.IsLoading; _doc.IsLoading = true; switch (eref.Name) { @@ -939,7 +948,7 @@ namespace System.Xml } Debug.Assert(tr.EntityHandling == EntityHandling.ExpandCharEntities); - XmlDocumentType dtdNode = doc.DocumentType; + XmlDocumentType? dtdNode = doc.DocumentType; if (dtdNode != null) { tr.Namespaces = dtdNode.ParseWithNamespaces; @@ -968,12 +977,12 @@ namespace System.Xml } #pragma warning restore 618 - internal static void ParseXmlDeclarationValue(string strValue, out string version, out string encoding, out string standalone) + internal static void ParseXmlDeclarationValue(string strValue, out string? version, out string? encoding, out string? standalone) { version = null; encoding = null; standalone = null; - XmlTextReaderImpl tempreader = new XmlTextReaderImpl(strValue, (XmlParserContext)null); + XmlTextReaderImpl tempreader = new XmlTextReaderImpl(strValue, (XmlParserContext?)null); try { tempreader.Read(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs index eeefd61..504245a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { using System.Text; @@ -12,12 +13,12 @@ namespace System.Xml private readonly string _prefix; private readonly string _localName; private readonly string _ns; - private string _name; + private string? _name; private readonly int _hashCode; internal XmlDocument ownerDoc; internal XmlName next; - public static XmlName Create(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next, IXmlSchemaInfo schemaInfo) + public static XmlName Create(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next, IXmlSchemaInfo? schemaInfo) { if (schemaInfo == null) { @@ -139,7 +140,7 @@ namespace System.Xml } } - public virtual XmlSchemaSimpleType MemberType + public virtual XmlSchemaSimpleType? MemberType { get { @@ -147,7 +148,7 @@ namespace System.Xml } } - public virtual XmlSchemaType SchemaType + public virtual XmlSchemaType? SchemaType { get { @@ -155,7 +156,7 @@ namespace System.Xml } } - public virtual XmlSchemaElement SchemaElement + public virtual XmlSchemaElement? SchemaElement { get { @@ -163,7 +164,7 @@ namespace System.Xml } } - public virtual XmlSchemaAttribute SchemaAttribute + public virtual XmlSchemaAttribute? SchemaAttribute { get { @@ -171,7 +172,7 @@ namespace System.Xml } } - public virtual bool Equals(IXmlSchemaInfo schemaInfo) + public virtual bool Equals(IXmlSchemaInfo? schemaInfo) { return schemaInfo == null; } @@ -190,9 +191,9 @@ namespace System.Xml internal sealed class XmlNameEx : XmlName { private byte _flags; - private readonly XmlSchemaSimpleType _memberType; - private readonly XmlSchemaType _schemaType; - private readonly object _decl; + private readonly XmlSchemaSimpleType? _memberType; + private readonly XmlSchemaType? _schemaType; + private readonly object? _decl; // flags // 0,1 : Validity @@ -211,7 +212,7 @@ namespace System.Xml _schemaType = schemaInfo.SchemaType; _decl = schemaInfo.SchemaElement != null ? (object)schemaInfo.SchemaElement - : (object)schemaInfo.SchemaAttribute; + : (object?)schemaInfo.SchemaAttribute; } public override XmlSchemaValidity Validity @@ -238,7 +239,7 @@ namespace System.Xml } } - public override XmlSchemaSimpleType MemberType + public override XmlSchemaSimpleType? MemberType { get { @@ -246,7 +247,7 @@ namespace System.Xml } } - public override XmlSchemaType SchemaType + public override XmlSchemaType? SchemaType { get { @@ -254,7 +255,7 @@ namespace System.Xml } } - public override XmlSchemaElement SchemaElement + public override XmlSchemaElement? SchemaElement { get { @@ -262,7 +263,7 @@ namespace System.Xml } } - public override XmlSchemaAttribute SchemaAttribute + public override XmlSchemaAttribute? SchemaAttribute { get { @@ -287,16 +288,16 @@ namespace System.Xml else _flags = (byte)(_flags & ~IsNilBit); } - public override bool Equals(IXmlSchemaInfo schemaInfo) + public override bool Equals(IXmlSchemaInfo? schemaInfo) { if (schemaInfo != null && schemaInfo.Validity == (XmlSchemaValidity)(_flags & ValidityMask) && schemaInfo.IsDefault == ((_flags & IsDefaultBit) != 0) && schemaInfo.IsNil == ((_flags & IsNilBit) != 0) - && (object)schemaInfo.MemberType == (object)_memberType - && (object)schemaInfo.SchemaType == (object)_schemaType - && (object)schemaInfo.SchemaElement == (object)(_decl as XmlSchemaElement) - && (object)schemaInfo.SchemaAttribute == (object)(_decl as XmlSchemaAttribute)) + && (object?)schemaInfo.MemberType == (object?)_memberType + && (object?)schemaInfo.SchemaType == (object?)_schemaType + && (object?)schemaInfo.SchemaElement == (object?)(_decl as XmlSchemaElement) + && (object?)schemaInfo.SchemaAttribute == (object?)(_decl as XmlSchemaAttribute)) { return true; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs index 6c738e0..a574034 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs @@ -1,8 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; using System.Collections.Generic; +using System.Diagnostics; namespace System.Xml { @@ -16,7 +18,7 @@ namespace System.Xml // object. // Otherwise, field is an List. Once the field upgrades to an List, it // never degrades back, even if all elements are removed. - private object _field; + private object? _field; public int Count { @@ -25,7 +27,7 @@ namespace System.Xml if (_field == null) return 0; - List list = _field as List; + List? list = _field as List; if (list != null) return list.Count; @@ -40,7 +42,7 @@ namespace System.Xml if (_field == null) throw new ArgumentOutOfRangeException(nameof(index)); - List list = _field as List; + List? list = _field as List; if (list != null) return list[index]; @@ -57,10 +59,11 @@ namespace System.Xml { if (value == null) { + Debug.Fail("Null was added to the collection which didn't expect it"); // If a single null value needs to be stored, then // upgrade to an ArrayList List temp = new List(); - temp.Add(null); + temp.Add(null!); _field = temp; } else @@ -69,7 +72,7 @@ namespace System.Xml return; } - List list = _field as List; + List? list = _field as List; if (list != null) { list.Add(value); @@ -88,7 +91,7 @@ namespace System.Xml if (_field == null) throw new ArgumentOutOfRangeException(nameof(index)); - List list = _field as List; + List? list = _field as List; if (list != null) { list.RemoveAt(index); @@ -111,7 +114,7 @@ namespace System.Xml return; } - List list = _field as List; + List? list = _field as List; if (list != null) { list.Insert(index, value); @@ -156,6 +159,7 @@ namespace System.Xml { throw new InvalidOperationException(); } + return _loneValue; } } @@ -167,6 +171,7 @@ namespace System.Xml _position = 0; return true; } + _position = 1; return false; } @@ -184,7 +189,7 @@ namespace System.Xml return XmlDocument.EmptyEnumerator; } - List list = _field as List; + List? list = _field as List; if (list != null) { return list.GetEnumerator(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs index 2ffb690..54b0c64 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; namespace System.Xml @@ -17,16 +18,17 @@ namespace System.Xml } // Retrieves a XmlNode specified by name. - public virtual XmlNode GetNamedItem(string name) + public virtual XmlNode? GetNamedItem(string name) { int offset = FindNodeOffset(name); if (offset >= 0) return (XmlNode)nodes[offset]; + return null; } // Adds a XmlNode using its Name property - public virtual XmlNode SetNamedItem(XmlNode node) + public virtual XmlNode? SetNamedItem(XmlNode? node) { if (node == null) return null; @@ -44,13 +46,14 @@ namespace System.Xml } // Removes the node specified by name. - public virtual XmlNode RemoveNamedItem(string name) + public virtual XmlNode? RemoveNamedItem(string name) { int offset = FindNodeOffset(name); if (offset >= 0) { return RemoveNodeAt(offset); } + return null; } @@ -64,7 +67,7 @@ namespace System.Xml } // Retrieves the node at the specified index in this XmlNamedNodeMap. - public virtual XmlNode Item(int index) + public virtual XmlNode? Item(int index) { if (index < 0 || index >= nodes.Count) return null; @@ -83,22 +86,24 @@ namespace System.Xml // // Retrieves a node specified by LocalName and NamespaceURI. - public virtual XmlNode GetNamedItem(string localName, string namespaceURI) + public virtual XmlNode? GetNamedItem(string localName, string? namespaceURI) { int offset = FindNodeOffset(localName, namespaceURI); if (offset >= 0) return (XmlNode)nodes[offset]; + return null; } // Removes a node specified by local name and namespace URI. - public virtual XmlNode RemoveNamedItem(string localName, string namespaceURI) + public virtual XmlNode? RemoveNamedItem(string localName, string? namespaceURI) { int offset = FindNodeOffset(localName, namespaceURI); if (offset >= 0) { return RemoveNodeAt(offset); } + return null; } @@ -121,7 +126,7 @@ namespace System.Xml return -1; } - internal int FindNodeOffset(string localName, string namespaceURI) + internal int FindNodeOffset(string localName, string? namespaceURI) { int c = this.Count; for (int i = 0; i < c; i++) @@ -137,13 +142,14 @@ namespace System.Xml internal virtual XmlNode AddNode(XmlNode node) { - XmlNode oldParent; + XmlNode? oldParent; if (node.NodeType == XmlNodeType.Attribute) oldParent = ((XmlAttribute)node).OwnerElement; else oldParent = node.ParentNode; - string nodeValue = node.Value; - XmlNodeChangedEventArgs args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); + + string? nodeValue = node.Value; + XmlNodeChangedEventArgs? args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); if (args != null) parent.BeforeEvent(args); @@ -159,17 +165,19 @@ namespace System.Xml internal virtual XmlNode AddNodeForLoad(XmlNode node, XmlDocument doc) { - XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(node, parent); + XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(node, parent); if (args != null) { doc.BeforeEvent(args); } + nodes.Add(node); node.SetParent(parent); if (args != null) { doc.AfterEvent(args); } + return node; } @@ -177,8 +185,8 @@ namespace System.Xml { XmlNode oldNode = (XmlNode)nodes[i]; - string oldNodeValue = oldNode.Value; - XmlNodeChangedEventArgs args = parent.GetEventArgs(oldNode, parent, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); + string? oldNodeValue = oldNode.Value; + XmlNodeChangedEventArgs? args = parent.GetEventArgs(oldNode, parent, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); if (args != null) parent.BeforeEvent(args); @@ -201,14 +209,14 @@ namespace System.Xml internal virtual XmlNode InsertNodeAt(int i, XmlNode node) { - XmlNode oldParent; + XmlNode? oldParent; if (node.NodeType == XmlNodeType.Attribute) oldParent = ((XmlAttribute)node).OwnerElement; else oldParent = node.ParentNode; - string nodeValue = node.Value; - XmlNodeChangedEventArgs args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); + string? nodeValue = node.Value; + XmlNodeChangedEventArgs? args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); if (args != null) parent.BeforeEvent(args); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs index a2e7c57..75e429e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.IO; using System.Collections; @@ -10,6 +11,7 @@ using System.Xml.Schema; using System.Xml.XPath; using MS.Internal.Xml.XPath; using System.Globalization; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -17,7 +19,7 @@ namespace System.Xml [DebuggerDisplay("{debuggerDisplayProxy}")] public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable { - internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly. + internal XmlNode? parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly. internal XmlNode() { @@ -27,61 +29,66 @@ namespace System.Xml { if (doc == null) throw new ArgumentException(SR.Xdom_Node_Null_Doc); + this.parentNode = doc; } - public virtual XPathNavigator CreateNavigator() + public virtual XPathNavigator? CreateNavigator() { - XmlDocument thisAsDoc = this as XmlDocument; + XmlDocument? thisAsDoc = this as XmlDocument; if (thisAsDoc != null) { return thisAsDoc.CreateNavigator(this); } - XmlDocument doc = OwnerDocument; + + XmlDocument? doc = OwnerDocument; Debug.Assert(doc != null); return doc.CreateNavigator(this); } // Selects the first node that matches the xpath expression - public XmlNode SelectSingleNode(string xpath) + public XmlNode? SelectSingleNode(string xpath) { - XmlNodeList list = SelectNodes(xpath); + XmlNodeList? list = SelectNodes(xpath); // SelectNodes returns null for certain node types return list != null ? list[0] : null; } // Selects the first node that matches the xpath expression and given namespace context. - public XmlNode SelectSingleNode(string xpath, XmlNamespaceManager nsmgr) + public XmlNode? SelectSingleNode(string xpath, XmlNamespaceManager nsmgr) { - XPathNavigator xn = (this).CreateNavigator(); + XPathNavigator? xn = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. if (xn == null) return null; + XPathExpression exp = xn.Compile(xpath); exp.SetContext(nsmgr); return new XPathNodeList(xn.Select(exp))[0]; } // Selects all nodes that match the xpath expression - public XmlNodeList SelectNodes(string xpath) + public XmlNodeList? SelectNodes(string xpath) { - XPathNavigator n = (this).CreateNavigator(); + XPathNavigator? n = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. if (n == null) return null; + return new XPathNodeList(n.Select(xpath)); } // Selects all nodes that match the xpath expression and given namespace context. - public XmlNodeList SelectNodes(string xpath, XmlNamespaceManager nsmgr) + public XmlNodeList? SelectNodes(string xpath, XmlNamespaceManager nsmgr) { - XPathNavigator xn = (this).CreateNavigator(); + XPathNavigator? xn = (this).CreateNavigator(); //if the method is called on node types like DocType, Entity, XmlDeclaration, //the navigator returned is null. So just return null from here for those node types. if (xn == null) return null; + XPathExpression exp = xn.Compile(xpath); exp.SetContext(nsmgr); return new XPathNodeList(xn.Select(exp)); @@ -94,7 +101,7 @@ namespace System.Xml } // Gets or sets the value of the node. - public virtual string Value + public virtual string? Value { get { return null; } set { throw new InvalidOperationException(SR.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); } @@ -107,7 +114,7 @@ namespace System.Xml } // Gets the parent of this node (for nodes that can have parents). - public virtual XmlNode ParentNode + public virtual XmlNode? ParentNode { get { @@ -119,21 +126,23 @@ namespace System.Xml } // Linear lookup through the children of the document - XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode; + XmlLinkedNode? firstChild = parentNode.FirstChild as XmlLinkedNode; if (firstChild != null) { - XmlLinkedNode node = firstChild; + XmlLinkedNode? node = firstChild; do { if (node == this) { return parentNode; } + node = node.next; } while (node != null && node != firstChild); } + return null; } } @@ -145,26 +154,26 @@ namespace System.Xml } // Gets the node immediately preceding this node. - public virtual XmlNode PreviousSibling + public virtual XmlNode? PreviousSibling { get { return null; } } // Gets the node immediately following this node. - public virtual XmlNode NextSibling + public virtual XmlNode? NextSibling { get { return null; } } // Gets a XmlAttributeCollection containing the attributes // of this node. - public virtual XmlAttributeCollection Attributes + public virtual XmlAttributeCollection? Attributes { get { return null; } } // Gets the XmlDocument that contains this node. - public virtual XmlDocument OwnerDocument + public virtual XmlDocument? OwnerDocument { get { @@ -176,11 +185,11 @@ namespace System.Xml } // Gets the first child of this node. - public virtual XmlNode FirstChild + public virtual XmlNode? FirstChild { get { - XmlLinkedNode linkedNode = LastNode; + XmlLinkedNode? linkedNode = LastNode; if (linkedNode != null) return linkedNode.next; @@ -189,7 +198,7 @@ namespace System.Xml } // Gets the last child of this node. - public virtual XmlNode LastChild + public virtual XmlNode? LastChild { get { return LastNode; } } @@ -199,7 +208,7 @@ namespace System.Xml get { return false; } } - internal virtual XmlLinkedNode LastNode + internal virtual XmlLinkedNode? LastNode { get { return null; } set { } @@ -207,7 +216,7 @@ namespace System.Xml internal bool AncestorNode(XmlNode node) { - XmlNode n = this.ParentNode; + XmlNode? n = this.ParentNode; while (n != null && n != this) { @@ -222,14 +231,14 @@ namespace System.Xml //trace to the top to find out its parent node. internal bool IsConnected() { - XmlNode parent = ParentNode; + XmlNode? parent = ParentNode; while (parent != null && !(parent.NodeType == XmlNodeType.Document)) parent = parent.ParentNode; return parent != null; } // Inserts the specified node immediately before the specified reference node. - public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) + public virtual XmlNode? InsertBefore(XmlNode newChild, XmlNode? refChild) { if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); @@ -246,8 +255,8 @@ namespace System.Xml if (newChild == refChild) return newChild; - XmlDocument childDoc = newChild.OwnerDocument; - XmlDocument thisDoc = OwnerDocument; + XmlDocument? childDoc = newChild.OwnerDocument; + XmlDocument? thisDoc = OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); @@ -260,8 +269,8 @@ namespace System.Xml // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { - XmlNode first = newChild.FirstChild; - XmlNode node = first; + XmlNode? first = newChild.FirstChild; + XmlNode? node = first; if (node != null) { newChild.RemoveChild(node); @@ -269,6 +278,7 @@ namespace System.Xml // insert the rest of the children after this one. InsertAfter(newChild, node); } + return first; } @@ -278,8 +288,8 @@ namespace System.Xml XmlLinkedNode newNode = (XmlLinkedNode)newChild; XmlLinkedNode refNode = (XmlLinkedNode)refChild; - string newChildValue = newChild.Value; - XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); + string? newChildValue = newChild.Value; + XmlNodeChangedEventArgs? args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); @@ -287,7 +297,7 @@ namespace System.Xml if (refNode == FirstChild) { newNode.next = refNode; - LastNode.next = newNode; + LastNode!.next = newNode; newNode.SetParent(this); if (newNode.IsText) @@ -300,7 +310,7 @@ namespace System.Xml } else { - XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling; + XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling!; newNode.next = refNode; prevNode.next = newNode; @@ -343,7 +353,7 @@ namespace System.Xml } // Inserts the specified node immediately after the specified reference node. - public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) + public virtual XmlNode? InsertAfter(XmlNode newChild, XmlNode? refChild) { if (this == newChild || AncestorNode(newChild)) throw new ArgumentException(SR.Xdom_Node_Insert_Child); @@ -360,8 +370,8 @@ namespace System.Xml if (newChild == refChild) return newChild; - XmlDocument childDoc = newChild.OwnerDocument; - XmlDocument thisDoc = OwnerDocument; + XmlDocument? childDoc = newChild.OwnerDocument; + XmlDocument? thisDoc = OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); @@ -375,11 +385,11 @@ namespace System.Xml if (newChild.NodeType == XmlNodeType.DocumentFragment) { XmlNode last = refChild; - XmlNode first = newChild.FirstChild; - XmlNode node = first; + XmlNode? first = newChild.FirstChild; + XmlNode? node = first; while (node != null) { - XmlNode next = node.NextSibling; + XmlNode? next = node.NextSibling; newChild.RemoveChild(node); InsertAfter(node, last); last = node; @@ -394,8 +404,8 @@ namespace System.Xml XmlLinkedNode newNode = (XmlLinkedNode)newChild; XmlLinkedNode refNode = (XmlLinkedNode)refChild; - string newChildValue = newChild.Value; - XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); + string? newChildValue = newChild.Value; + XmlNodeChangedEventArgs? args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); @@ -417,7 +427,7 @@ namespace System.Xml } else { - XmlLinkedNode nextNode = refNode.next; + XmlLinkedNode nextNode = refNode.next!; newNode.next = nextNode; refNode.next = newNode; @@ -463,9 +473,9 @@ namespace System.Xml // Replaces the child node oldChild with newChild node. public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) { - XmlNode nextNode = oldChild.NextSibling; + XmlNode? nextNode = oldChild.NextSibling; RemoveChild(oldChild); - XmlNode node = InsertBefore(newChild, nextNode); + XmlNode? node = InsertBefore(newChild, nextNode); return oldChild; } @@ -480,13 +490,13 @@ namespace System.Xml XmlLinkedNode oldNode = (XmlLinkedNode)oldChild; - string oldNodeValue = oldNode.Value; - XmlNodeChangedEventArgs args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); + string? oldNodeValue = oldNode.Value; + XmlNodeChangedEventArgs? args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); if (args != null) BeforeEvent(args); - XmlLinkedNode lastNode = LastNode; + XmlLinkedNode? lastNode = LastNode; if (oldNode == FirstChild) { @@ -498,7 +508,7 @@ namespace System.Xml } else { - XmlLinkedNode nextNode = oldNode.next; + XmlLinkedNode nextNode = oldNode.next!; if (nextNode.IsText) { @@ -508,7 +518,7 @@ namespace System.Xml } } - lastNode.next = nextNode; + lastNode!.next = nextNode; oldNode.next = null; oldNode.SetParent(null); } @@ -517,7 +527,7 @@ namespace System.Xml { if (oldNode == lastNode) { - XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling; + XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling!; prevNode.next = oldNode.next; LastNode = prevNode; oldNode.next = null; @@ -525,8 +535,8 @@ namespace System.Xml } else { - XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling; - XmlLinkedNode nextNode = oldNode.next; + XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling!; + XmlLinkedNode nextNode = oldNode.next!; if (nextNode.IsText) { @@ -556,15 +566,15 @@ namespace System.Xml } // Adds the specified node to the beginning of the list of children of this node. - public virtual XmlNode PrependChild(XmlNode newChild) + public virtual XmlNode? PrependChild(XmlNode newChild) { return InsertBefore(newChild, FirstChild); } // Adds the specified node to the end of the list of children of this node. - public virtual XmlNode AppendChild(XmlNode newChild) + public virtual XmlNode? AppendChild(XmlNode newChild) { - XmlDocument thisDoc = OwnerDocument; + XmlDocument? thisDoc = OwnerDocument; if (thisDoc == null) { thisDoc = this as XmlDocument; @@ -578,22 +588,23 @@ namespace System.Xml if (newChild.ParentNode != null) newChild.ParentNode.RemoveChild(newChild); - XmlDocument childDoc = newChild.OwnerDocument; + XmlDocument? childDoc = newChild.OwnerDocument; if (childDoc != null && childDoc != thisDoc && childDoc != this) throw new ArgumentException(SR.Xdom_Node_Insert_Context); // special case for doc-fragment. if (newChild.NodeType == XmlNodeType.DocumentFragment) { - XmlNode first = newChild.FirstChild; - XmlNode node = first; + XmlNode? first = newChild.FirstChild; + XmlNode? node = first; while (node != null) { - XmlNode next = node.NextSibling; + XmlNode? next = node.NextSibling; newChild.RemoveChild(node); AppendChild(node); node = next; } + return first; } @@ -604,13 +615,13 @@ namespace System.Xml if (!CanInsertAfter(newChild, LastChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); - string newChildValue = newChild.Value; - XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); + string? newChildValue = newChild.Value; + XmlNodeChangedEventArgs? args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert); if (args != null) BeforeEvent(args); - XmlLinkedNode refNode = LastNode; + XmlLinkedNode? refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (refNode == null) @@ -644,12 +655,12 @@ namespace System.Xml //the function is provided only at Load time to speed up Load process internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { - XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this); + XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); - XmlLinkedNode refNode = LastNode; + XmlLinkedNode? refNode = LastNode; XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (refNode == null) @@ -685,12 +696,12 @@ namespace System.Xml return false; } - internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode refChild) + internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode? refChild) { return true; } - internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode refChild) + internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) { return true; } @@ -706,7 +717,7 @@ namespace System.Xml internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep) { - for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = container.FirstChild; child != null; child = child.NextSibling) { AppendChildForLoad(child.CloneNode(deep), doc); } @@ -721,11 +732,11 @@ namespace System.Xml // are no adjacent XmlText nodes. public virtual void Normalize() { - XmlNode firstChildTextLikeNode = null; + XmlNode? firstChildTextLikeNode = null; StringBuilder sb = StringBuilderCache.Acquire(); - for (XmlNode crtChild = this.FirstChild; crtChild != null;) + for (XmlNode? crtChild = this.FirstChild; crtChild != null;) { - XmlNode nextChild = crtChild.NextSibling; + XmlNode? nextChild = crtChild.NextSibling; switch (crtChild.NodeType) { case XmlNodeType.Text: @@ -733,7 +744,7 @@ namespace System.Xml case XmlNodeType.SignificantWhitespace: { sb.Append(crtChild.Value); - XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild); + XmlNode? winner = NormalizeWinner(firstChildTextLikeNode, crtChild); if (winner == firstChildTextLikeNode) { this.RemoveChild(crtChild); @@ -744,6 +755,7 @@ namespace System.Xml this.RemoveChild(firstChildTextLikeNode); firstChildTextLikeNode = crtChild; } + break; } case XmlNodeType.Element: @@ -758,6 +770,7 @@ namespace System.Xml firstChildTextLikeNode.Value = sb.ToString(); firstChildTextLikeNode = null; } + sb.Remove(0, sb.Length); break; } @@ -770,7 +783,7 @@ namespace System.Xml StringBuilderCache.Release(sb); } - private XmlNode NormalizeWinner(XmlNode firstNode, XmlNode secondNode) + private XmlNode? NormalizeWinner(XmlNode? firstNode, XmlNode secondNode) { //first node has the priority if (firstNode == null) @@ -834,12 +847,12 @@ namespace System.Xml { get { - XmlDocument doc = OwnerDocument; + XmlDocument? doc = OwnerDocument; return HasReadOnlyParent(this); } } - internal static bool HasReadOnlyParent(XmlNode n) + internal static bool HasReadOnlyParent(XmlNode? n) { while (n != null) { @@ -886,7 +899,7 @@ namespace System.Xml private void AppendChildText(StringBuilder builder) { - for (XmlNode child = FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = FirstChild; child != null; child = child.NextSibling) { if (child.FirstChild == null) { @@ -907,7 +920,7 @@ namespace System.Xml { get { - XmlNode fc = FirstChild; + XmlNode? fc = FirstChild; if (fc == null) { return string.Empty; @@ -921,9 +934,10 @@ namespace System.Xml case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: - return fc.Value; + return fc.Value!; } } + StringBuilder builder = StringBuilderCache.Acquire(); AppendChildText(builder); return StringBuilderCache.GetStringAndRelease(builder); @@ -931,7 +945,7 @@ namespace System.Xml set { - XmlNode firstChild = FirstChild; + XmlNode? firstChild = FirstChild; if (firstChild != null //there is one child && firstChild.NextSibling == null // and exactly one && firstChild.NodeType == XmlNodeType.Text)//which is a text node @@ -942,7 +956,7 @@ namespace System.Xml else { RemoveAll(); - AppendChild(OwnerDocument.CreateTextNode(value)); + AppendChild(OwnerDocument!.CreateTextNode(value)); } } } @@ -1002,7 +1016,7 @@ namespace System.Xml { get { - XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref + XmlNode? curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref while (curNode != null) { XmlNodeType nt = curNode.NodeType; @@ -1030,8 +1044,8 @@ namespace System.Xml // of the current node. public virtual void RemoveAll() { - XmlNode child = FirstChild; - XmlNode sibling = null; + XmlNode? child = FirstChild; + XmlNode? sibling = null; while (child != null) { @@ -1047,7 +1061,7 @@ namespace System.Xml { if (NodeType == XmlNodeType.Document) return (XmlDocument)this; - return OwnerDocument; + return OwnerDocument!; } } @@ -1056,20 +1070,22 @@ namespace System.Xml // the namespace URI in the declaration. public virtual string GetNamespaceOfPrefix(string prefix) { - string namespaceName = GetNamespaceOfPrefixStrict(prefix); - return namespaceName != null ? namespaceName : string.Empty; + string? namespaceName = GetNamespaceOfPrefixStrict(prefix); + return namespaceName ?? string.Empty; } - internal string GetNamespaceOfPrefixStrict(string prefix) + internal string? GetNamespaceOfPrefixStrict(string prefix) { XmlDocument doc = Document; + string? pref = prefix; + if (doc != null) { - prefix = doc.NameTable.Get(prefix); - if (prefix == null) + pref = doc.NameTable.Get(pref); + if (pref == null) return null; - XmlNode node = this; + XmlNode? node = this; while (node != null) { if (node.NodeType == XmlNodeType.Element) @@ -1078,7 +1094,7 @@ namespace System.Xml if (elem.HasAttributes) { XmlAttributeCollection attrs = elem.Attributes; - if (prefix.Length == 0) + if (pref.Length == 0) { for (int iAttr = 0; iAttr < attrs.Count; iAttr++) { @@ -1099,19 +1115,19 @@ namespace System.Xml XmlAttribute attr = attrs[iAttr]; if (Ref.Equal(attr.Prefix, doc.strXmlns)) { - if (Ref.Equal(attr.LocalName, prefix)) + if (Ref.Equal(attr.LocalName, pref)) { return attr.Value; // found xmlns:prefix } } - else if (Ref.Equal(attr.Prefix, prefix)) + else if (Ref.Equal(attr.Prefix, pref)) { return attr.NamespaceURI; // found prefix:attr } } } } - if (Ref.Equal(node.Prefix, prefix)) + if (Ref.Equal(node.Prefix, pref)) { return node.NamespaceURI; } @@ -1126,15 +1142,16 @@ namespace System.Xml node = node.ParentNode; } } - if (Ref.Equal(doc.strXml, prefix)) + if (Ref.Equal(doc.strXml, pref)) { // xmlns:xml return doc.strReservedXml; } - else if (Ref.Equal(doc.strXmlns, prefix)) + else if (Ref.Equal(doc.strXmlns, pref)) { // xmlns:xmlns return doc.strReservedXmlns; } } + return null; } @@ -1143,18 +1160,18 @@ namespace System.Xml // the prefix defined in that declaration. public virtual string GetPrefixOfNamespace(string namespaceURI) { - string prefix = GetPrefixOfNamespaceStrict(namespaceURI); + string? prefix = GetPrefixOfNamespaceStrict(namespaceURI); return prefix != null ? prefix : string.Empty; } - internal string GetPrefixOfNamespaceStrict(string namespaceURI) + internal string? GetPrefixOfNamespaceStrict(string namespaceURI) { XmlDocument doc = Document; if (doc != null) { namespaceURI = doc.NameTable.Add(namespaceURI); - XmlNode node = this; + XmlNode? node = this; while (node != null) { if (node.NodeType == XmlNodeType.Element) @@ -1214,39 +1231,42 @@ namespace System.Xml return doc.strXmlns; } } + return null; } // Retrieves the first child element with the specified name. - public virtual XmlElement this[string name] + public virtual XmlElement? this[string name] { get { - for (XmlNode n = FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.Name == name) return (XmlElement)n; } + return null; } } // Retrieves the first child element with the specified LocalName and // NamespaceURI. - public virtual XmlElement this[string localname, string ns] + public virtual XmlElement? this[string localname, string ns] { get { - for (XmlNode n = FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns) return (XmlElement)n; } + return null; } } - internal virtual void SetParent(XmlNode node) + internal virtual void SetParent(XmlNode? node) { if (node == null) { @@ -1278,21 +1298,22 @@ namespace System.Xml } } - internal virtual XmlNode FindChild(XmlNodeType type) + internal virtual XmlNode? FindChild(XmlNodeType type) { - for (XmlNode child = FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = FirstChild; child != null; child = child.NextSibling) { if (child.NodeType == type) { return child; } } + return null; } - internal virtual XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) + internal virtual XmlNodeChangedEventArgs? GetEventArgs(XmlNode node, XmlNode? oldParent, XmlNode? newParent, string? oldValue, string? newValue, XmlNodeChangedAction action) { - XmlDocument doc = OwnerDocument; + XmlDocument? doc = OwnerDocument; if (doc != null) { if (!doc.IsLoading) @@ -1300,29 +1321,31 @@ namespace System.Xml if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly))) throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly); } + return doc.GetEventArgs(node, oldParent, newParent, oldValue, newValue, action); } + return null; } internal virtual void BeforeEvent(XmlNodeChangedEventArgs args) { if (args != null) - OwnerDocument.BeforeEvent(args); + OwnerDocument!.BeforeEvent(args); } internal virtual void AfterEvent(XmlNodeChangedEventArgs args) { if (args != null) - OwnerDocument.AfterEvent(args); + OwnerDocument!.AfterEvent(args); } internal virtual XmlSpace XmlSpace { get { - XmlNode node = this; - XmlElement elem = null; + XmlNode? node = this; + XmlElement? elem = null; do { elem = node as XmlElement; @@ -1339,9 +1362,10 @@ namespace System.Xml break; } } + node = node.ParentNode; - } - while (node != null); + } while (node != null); + return XmlSpace.None; } } @@ -1350,8 +1374,8 @@ namespace System.Xml { get { - XmlNode node = this; - XmlElement elem = null; + XmlNode? node = this; + XmlElement? elem = null; do { elem = node as XmlElement; @@ -1360,8 +1384,10 @@ namespace System.Xml if (elem.HasAttribute("xml:lang")) return elem.GetAttribute("xml:lang"); } + node = node.ParentNode; } while (node != null); + return string.Empty; } } @@ -1382,7 +1408,7 @@ namespace System.Xml } } - internal virtual string GetXPAttribute(string localName, string namespaceURI) + internal virtual string? GetXPAttribute(string localName, string namespaceURI) { return string.Empty; } @@ -1395,7 +1421,7 @@ namespace System.Xml } } - public virtual XmlNode PreviousText + public virtual XmlNode? PreviousText { get { @@ -1443,7 +1469,7 @@ namespace System.Xml break; case XmlNodeType.Attribute: case XmlNodeType.ProcessingInstruction: - result += ", Name=\"" + _node.Name + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value) + "\""; + result += ", Name=\"" + _node.Name + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value!) + "\""; break; case XmlNodeType.Text: case XmlNodeType.CDATA: @@ -1451,11 +1477,11 @@ namespace System.Xml case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.XmlDeclaration: - result += ", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value) + "\""; + result += ", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value!) + "\""; break; case XmlNodeType.DocumentType: XmlDocumentType documentType = (XmlDocumentType)_node; - result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(documentType.InternalSubset) + "\""; + result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(documentType.InternalSubset!) + "\""; break; default: break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventArgs.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventArgs.cs index 6ab108f..d89ed2f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventArgs.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventArgs.cs @@ -1,18 +1,19 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { public class XmlNodeChangedEventArgs : EventArgs { private readonly XmlNodeChangedAction _action; - private readonly XmlNode _node; - private readonly XmlNode _oldParent; - private readonly XmlNode _newParent; - private readonly string _oldValue; - private readonly string _newValue; + private readonly XmlNode? _node; + private readonly XmlNode? _oldParent; + private readonly XmlNode? _newParent; + private readonly string? _oldValue; + private readonly string? _newValue; - public XmlNodeChangedEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) + public XmlNodeChangedEventArgs(XmlNode? node, XmlNode? oldParent, XmlNode? newParent, string? oldValue, string? newValue, XmlNodeChangedAction action) { _node = node; _oldParent = oldParent; @@ -24,14 +25,14 @@ namespace System.Xml public XmlNodeChangedAction Action { get { return _action; } } - public XmlNode Node { get { return _node; } } + public XmlNode? Node { get { return _node; } } - public XmlNode OldParent { get { return _oldParent; } } + public XmlNode? OldParent { get { return _oldParent; } } - public XmlNode NewParent { get { return _newParent; } } + public XmlNode? NewParent { get { return _newParent; } } - public string OldValue { get { return _oldValue; } } + public string? OldValue { get { return _oldValue; } } - public string NewValue { get { return _newValue; } } + public string? NewValue { get { return _newValue; } } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventHandler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventHandler.cs index b63ac81..d106cea 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventHandler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventHandler.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { public delegate void XmlNodeChangedEventHandler(object sender, XmlNodeChangedEventArgs e); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeList.cs index 2c14561..0565f52 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeList.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; namespace System.Xml @@ -9,7 +10,7 @@ namespace System.Xml public abstract class XmlNodeList : IEnumerable, IDisposable { // Retrieves a node at the given index. - public abstract XmlNode Item(int index); + public abstract XmlNode? Item(int index); // Gets the number of nodes in this XmlNodeList. public abstract int Count { get; } @@ -20,7 +21,7 @@ namespace System.Xml // Retrieves a node at the given index. [System.Runtime.CompilerServices.IndexerName("ItemOf")] - public virtual XmlNode this[int i] { get { return Item(i); } } + public virtual XmlNode? this[int i] { get { return Item(i); } } void IDisposable.Dispose() { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs index 4ed38db..b3a255c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { using System; @@ -15,7 +16,7 @@ namespace System.Xml internal class XmlNodeReaderNavigator { private XmlNode _curNode; - private XmlNode _elemNode; + private XmlNode? _elemNode; private XmlNode _logNode; private int _attrIndex; private int _logAttrIndex; @@ -45,10 +46,10 @@ namespace System.Xml internal struct VirtualAttribute { - internal string name; - internal string value; + internal string? name; + internal string? value; - internal VirtualAttribute(string name, string value) + internal VirtualAttribute(string? name, string? value) { this.name = name; this.value = value; @@ -89,7 +90,8 @@ namespace System.Xml if (nt == XmlNodeType.Document) _doc = (XmlDocument)_curNode; else - _doc = node.OwnerDocument; + _doc = node.OwnerDocument!; + _nameTable = _doc.NameTable; _nAttrInd = -1; //initialize the caching variables @@ -134,9 +136,9 @@ namespace System.Xml { Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount); if (_curNode.NodeType == XmlNodeType.XmlDeclaration) - return decNodeAttributes[_nAttrInd].name; + return decNodeAttributes[_nAttrInd].name!; else - return docTypeNodeAttributes[_nAttrInd].name; + return docTypeNodeAttributes[_nAttrInd].name!; } } if (IsLocalNameEmpty(_curNode.NodeType)) @@ -225,7 +227,7 @@ namespace System.Xml //See comments in HasValue get { - string retValue = null; + string? retValue = null; XmlNodeType nt = _curNode.NodeType; if (_nAttrInd != -1) { @@ -233,9 +235,9 @@ namespace System.Xml Debug.Assert(nt == XmlNodeType.XmlDeclaration || nt == XmlNodeType.DocumentType); Debug.Assert(_nAttrInd >= 0 && _nAttrInd < AttributeCount); if (_curNode.NodeType == XmlNodeType.XmlDeclaration) - return decNodeAttributes[_nAttrInd].value; + return decNodeAttributes[_nAttrInd].value!; else - return docTypeNodeAttributes[_nAttrInd].value; + return docTypeNodeAttributes[_nAttrInd].value!; } if (nt == XmlNodeType.DocumentType) retValue = ((XmlDocumentType)_curNode).InternalSubset; //in this case nav.Value will be null @@ -321,7 +323,7 @@ namespace System.Xml return ((XmlElement)_curNode).Attributes.Count; else if (nt == XmlNodeType.Attribute || (_bOnAttrVal && nt != XmlNodeType.XmlDeclaration && nt != XmlNodeType.DocumentType)) - return _elemNode.Attributes.Count; + return _elemNode!.Attributes!.Count; else if (nt == XmlNodeType.XmlDeclaration) { if (_nDeclarationAttrCount != -1) @@ -352,7 +354,7 @@ namespace System.Xml private void InitDecAttr() { int i = 0; - string strTemp = _doc.Version; + string? strTemp = _doc.Version; if (strTemp != null && strTemp.Length != 0) { decNodeAttributes[i].name = strVersion; @@ -376,7 +378,7 @@ namespace System.Xml _nDeclarationAttrCount = i; } - public string GetDeclarationAttr(XmlDeclaration decl, string name) + public string? GetDeclarationAttr(XmlDeclaration decl, string name) { //PreCondition: curNode is pointing at Declaration node or one of its virtual attributes if (name == strVersion) @@ -388,7 +390,7 @@ namespace System.Xml return null; } - public string GetDeclarationAttr(int i) + public string? GetDeclarationAttr(int i) { if (_nDeclarationAttrCount == -1) InitDecAttr(); @@ -410,19 +412,21 @@ namespace System.Xml private void InitDocTypeAttr() { int i = 0; - XmlDocumentType docType = _doc.DocumentType; + XmlDocumentType? docType = _doc.DocumentType; if (docType == null) { _nDocTypeAttrCount = 0; return; } - string strTemp = docType.PublicId; + + string? strTemp = docType.PublicId; if (strTemp != null) { docTypeNodeAttributes[i].name = strPublicID; docTypeNodeAttributes[i].value = strTemp; i++; } + strTemp = docType.SystemId; if (strTemp != null) { @@ -430,10 +434,11 @@ namespace System.Xml docTypeNodeAttributes[i].value = strTemp; i++; } + _nDocTypeAttrCount = i; } - public string GetDocumentTypeAttr(XmlDocumentType docType, string name) + public string? GetDocumentTypeAttr(XmlDocumentType docType, string name) { //PreCondition: nav is pointing at DocumentType node or one of its virtual attributes if (name == strPublicID) @@ -443,7 +448,7 @@ namespace System.Xml return null; } - public string GetDocumentTypeAttr(int i) + public string? GetDocumentTypeAttr(int i) { if (_nDocTypeAttrCount == -1) InitDocTypeAttr(); @@ -462,37 +467,37 @@ namespace System.Xml return -1; } - private string GetAttributeFromElement(XmlElement elem, string name) + private string? GetAttributeFromElement(XmlElement elem, string name) { - XmlAttribute attr = elem.GetAttributeNode(name); + XmlAttribute? attr = elem.GetAttributeNode(name); if (attr != null) return attr.Value; return null; } - public string GetAttribute(string name) + public string? GetAttribute(string name) { if (_bCreatedOnAttribute) return null; return _curNode.NodeType switch { - XmlNodeType.Element => GetAttributeFromElement((XmlElement)_curNode, name), - XmlNodeType.Attribute => GetAttributeFromElement((XmlElement)_elemNode, name), + XmlNodeType.Element => GetAttributeFromElement((XmlElement)_curNode!, name), + XmlNodeType.Attribute => GetAttributeFromElement((XmlElement)_elemNode!, name), XmlNodeType.XmlDeclaration => GetDeclarationAttr((XmlDeclaration)_curNode, name), XmlNodeType.DocumentType => GetDocumentTypeAttr((XmlDocumentType)_curNode, name), _ => null, }; } - private string GetAttributeFromElement(XmlElement elem, string name, string ns) + private string? GetAttributeFromElement(XmlElement elem, string name, string? ns) { - XmlAttribute attr = elem.GetAttributeNode(name, ns); + XmlAttribute? attr = elem.GetAttributeNode(name, ns); if (attr != null) return attr.Value; return null; } - public string GetAttribute(string name, string ns) + public string? GetAttribute(string name, string ns) { if (_bCreatedOnAttribute) return null; @@ -500,14 +505,14 @@ namespace System.Xml return _curNode.NodeType switch { XmlNodeType.Element => GetAttributeFromElement((XmlElement)_curNode, name, ns), - XmlNodeType.Attribute => GetAttributeFromElement((XmlElement)_elemNode, name, ns), + XmlNodeType.Attribute => GetAttributeFromElement((XmlElement)_elemNode!, name, ns), XmlNodeType.XmlDeclaration => (ns.Length == 0) ? GetDeclarationAttr((XmlDeclaration)_curNode, name) : null, XmlNodeType.DocumentType => (ns.Length == 0) ? GetDocumentTypeAttr((XmlDocumentType)_curNode, name) : null, _ => null, }; } - public string GetAttribute(int attributeIndex) + public string? GetAttribute(int attributeIndex) { if (_bCreatedOnAttribute) return null; @@ -518,7 +523,7 @@ namespace System.Xml return ((XmlElement)_curNode).Attributes[attributeIndex].Value; case XmlNodeType.Attribute: CheckIndexCondition(attributeIndex); - return ((XmlElement)_elemNode).Attributes[attributeIndex].Value; + return ((XmlElement)_elemNode!).Attributes[attributeIndex].Value; case XmlNodeType.XmlDeclaration: { CheckIndexCondition(attributeIndex); @@ -576,9 +581,10 @@ namespace System.Xml } else { - while (_curNode.NodeType != XmlNodeType.Attribute && ((_curNode = _curNode.ParentNode) != null)) + while (_curNode.NodeType != XmlNodeType.Attribute && ((_curNode = _curNode.ParentNode!) != null)) level--; } + _bOnAttrVal = false; } } @@ -606,7 +612,7 @@ namespace System.Xml ResetToAttribute(ref level); if (_curNode.NodeType == XmlNodeType.Attribute) { - _curNode = ((XmlAttribute)_curNode).OwnerElement; + _curNode = ((XmlAttribute)_curNode).OwnerElement!; _attrIndex = -1; level--; nt = XmlNodeType.Element; @@ -621,7 +627,7 @@ namespace System.Xml } private bool MoveToAttributeFromElement(XmlElement elem, string name, string ns) { - XmlAttribute attr = null; + XmlAttribute? attr = null; if (ns.Length == 0) attr = elem.GetAttributeNode(name); else @@ -648,7 +654,7 @@ namespace System.Xml if (nt == XmlNodeType.Element) return MoveToAttributeFromElement((XmlElement)_curNode, name, namespaceURI); else if (nt == XmlNodeType.Attribute) - return MoveToAttributeFromElement((XmlElement)_elemNode, name, namespaceURI); + return MoveToAttributeFromElement((XmlElement)_elemNode!, name, namespaceURI); else if (nt == XmlNodeType.XmlDeclaration && namespaceURI.Length == 0) { if ((_nAttrInd = GetDecAttrInd(name)) != -1) @@ -672,7 +678,7 @@ namespace System.Xml { if (_bCreatedOnAttribute) return; - XmlAttribute attr = null; + XmlAttribute? attr = null; switch (_curNode.NodeType) { case XmlNodeType.Element: @@ -687,7 +693,7 @@ namespace System.Xml break; case XmlNodeType.Attribute: CheckIndexCondition(attributeIndex); - attr = ((XmlElement)_elemNode).Attributes[attributeIndex]; + attr = ((XmlElement)_elemNode!).Attributes[attributeIndex]; if (attr != null) { _curNode = (XmlNode)attr; @@ -709,7 +715,7 @@ namespace System.Xml XmlNodeType nt = _curNode.NodeType; if (nt == XmlNodeType.Attribute) { - if (_attrIndex >= (_elemNode.Attributes.Count - 1)) + if (_attrIndex >= (_elemNode!.Attributes!.Count - 1)) return false; else { @@ -719,7 +725,7 @@ namespace System.Xml } else if (nt == XmlNodeType.Element) { - if (_curNode.Attributes.Count > 0) + if (_curNode.Attributes!.Count > 0) { level++; _elemNode = _curNode; @@ -759,7 +765,7 @@ namespace System.Xml public bool MoveToParent() { - XmlNode parent = _curNode.ParentNode; + XmlNode? parent = _curNode.ParentNode; if (parent != null) { _curNode = parent; @@ -772,7 +778,7 @@ namespace System.Xml public bool MoveToFirstChild() { - XmlNode firstChild = _curNode.FirstChild; + XmlNode? firstChild = _curNode.FirstChild; if (firstChild != null) { _curNode = firstChild; @@ -780,12 +786,13 @@ namespace System.Xml _attrIndex = -1; return true; } + return false; } private bool MoveToNextSibling(XmlNode node) { - XmlNode nextSibling = node.NextSibling; + XmlNode? nextSibling = node.NextSibling; if (nextSibling != null) { _curNode = nextSibling; @@ -793,6 +800,7 @@ namespace System.Xml _attrIndex = -1; return true; } + return false; } @@ -801,7 +809,7 @@ namespace System.Xml if (_curNode.NodeType != XmlNodeType.Attribute) return MoveToNextSibling(_curNode); else - return MoveToNextSibling(_elemNode); + return MoveToNextSibling(_elemNode!); } public bool MoveToElement() @@ -832,7 +840,7 @@ namespace System.Xml return false; } - public string LookupNamespace(string prefix) + public string? LookupNamespace(string prefix) { if (_bCreatedOnAttribute) return null; @@ -855,7 +863,7 @@ namespace System.Xml attrName = "xmlns:" + prefix; // walk up the XmlNode parent chain, looking for the xmlns attribute - XmlNode node = _curNode; + XmlNode? node = _curNode; while (node != null) { if (node.NodeType == XmlNodeType.Element) @@ -863,7 +871,7 @@ namespace System.Xml XmlElement elem = (XmlElement)node; if (elem.HasAttributes) { - XmlAttribute attr = elem.GetAttributeNode(attrName); + XmlAttribute? attr = elem.GetAttributeNode(attrName); if (attr != null) { return attr.Value; @@ -884,7 +892,7 @@ namespace System.Xml return null; } - internal string DefaultLookupNamespace(string prefix) + internal string? DefaultLookupNamespace(string prefix) { if (!_bCreatedOnAttribute) { @@ -904,7 +912,7 @@ namespace System.Xml return null; } - internal string LookupPrefix(string namespaceName) + internal string? LookupPrefix(string namespaceName) { if (_bCreatedOnAttribute || namespaceName == null) { @@ -923,7 +931,7 @@ namespace System.Xml return string.Empty; } // walk up the XmlNode parent chain, looking for the xmlns attribute with namespaceName value - XmlNode node = _curNode; + XmlNode? node = _curNode; while (node != null) { if (node.NodeType == XmlNodeType.Element) @@ -961,8 +969,10 @@ namespace System.Xml node = ((XmlAttribute)node).OwnerElement; continue; } + node = node.ParentNode; } + return null; } @@ -973,7 +983,7 @@ namespace System.Xml return dict; // walk up the XmlNode parent chain and add all namespace declarations to the dictionary - XmlNode node = _curNode; + XmlNode? node = _curNode; while (node != null) { if (node.NodeType == XmlNodeType.Element) @@ -989,7 +999,7 @@ namespace System.Xml { if (!dict.ContainsKey(string.Empty)) { - dict.Add(_nameTable.Add(string.Empty), _nameTable.Add(a.Value)); + dict.Add(_nameTable.Add(string.Empty), _nameTable.Add(a.Value!)); } } else if (a.Prefix == "xmlns") @@ -997,7 +1007,7 @@ namespace System.Xml string localName = a.LocalName; if (!dict.ContainsKey(localName)) { - dict.Add(_nameTable.Add(localName), _nameTable.Add(a.Value)); + dict.Add(_nameTable.Add(localName), _nameTable.Add(a.Value!)); } } } @@ -1012,6 +1022,7 @@ namespace System.Xml node = ((XmlAttribute)node).OwnerElement; continue; } + node = node.ParentNode; }; @@ -1045,7 +1056,7 @@ namespace System.Xml } if (_curNode.NodeType == XmlNodeType.Attribute) { - XmlNode firstChild = _curNode.FirstChild; + XmlNode? firstChild = _curNode.FirstChild; if (firstChild != null) { _curNode = firstChild; @@ -1057,13 +1068,13 @@ namespace System.Xml } else if (_bOnAttrVal) { - XmlNode nextSibling = null; + XmlNode? nextSibling = null; if (_curNode.NodeType == XmlNodeType.EntityReference && bResolveEntity) { //going down to ent ref node - _curNode = _curNode.FirstChild; - nt = _curNode.NodeType; + _curNode = _curNode.FirstChild!; Debug.Assert(_curNode != null); + nt = _curNode.NodeType; level++; bResolveEntity = false; return true; @@ -1072,7 +1083,7 @@ namespace System.Xml nextSibling = _curNode.NextSibling; if (nextSibling == null) { - XmlNode parentNode = _curNode.ParentNode; + XmlNode? parentNode = _curNode.ParentNode; //Check if its parent is entity ref node is sufficient, because in this senario, ent ref node can't have more than 1 level of children that are not other ent ref nodes if (parentNode != null && parentNode.NodeType == XmlNodeType.EntityReference) { @@ -1119,7 +1130,7 @@ namespace System.Xml private bool _bStartFromDocument; private bool _bInReadBinary; - private ReadContentAsBinaryHelper _readBinaryHelper; + private ReadContentAsBinaryHelper? _readBinaryHelper; // Creates an instance of the XmlNodeReader class using the specified XmlNode. @@ -1129,6 +1140,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(node)); } + _readerNav = new XmlNodeReaderNavigator(node); _curDepth = 0; @@ -1290,7 +1302,7 @@ namespace System.Xml } } - public override IXmlSchemaInfo SchemaInfo + public override IXmlSchemaInfo? SchemaInfo { get { @@ -1318,7 +1330,7 @@ namespace System.Xml } // Gets the value of the attribute with the specified name. - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { //if not on Attribute, only element node could have attributes if (!IsInReadingStates()) @@ -1327,7 +1339,7 @@ namespace System.Xml } // Gets the value of the attribute with the specified name and namespace. - public override string GetAttribute(string name, string namespaceURI) + public override string? GetAttribute(string name, string? namespaceURI) { //if not on Attribute, only element node could have attributes if (!IsInReadingStates()) @@ -1343,7 +1355,7 @@ namespace System.Xml throw new ArgumentOutOfRangeException(nameof(attributeIndex)); //CheckIndexCondition( i ); //Debug.Assert( nav.NodeType == XmlNodeType.Element ); - return _readerNav.GetAttribute(attributeIndex); + return _readerNav.GetAttribute(attributeIndex)!; } // Moves to the attribute with the specified name. @@ -1367,7 +1379,7 @@ namespace System.Xml } // Moves to the attribute with the specified name and namespace. - public override bool MoveToAttribute(string name, string namespaceURI) + public override bool MoveToAttribute(string name, string? namespaceURI) { if (!IsInReadingStates()) return false; @@ -1743,11 +1755,11 @@ namespace System.Xml } // Resolves a namespace prefix in the current element's scope. - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { if (!IsInReadingStates()) return null; - string ns = _readerNav.LookupNamespace(prefix); + string? ns = _readerNav.LookupNamespace(prefix); if (ns != null && ns.Length == 0) { return null; @@ -1802,7 +1814,7 @@ namespace System.Xml _bInReadBinary = false; // call to the helper - int readCount = _readBinaryHelper.ReadContentAsBase64(buffer, index, count); + int readCount = _readBinaryHelper!.ReadContentAsBase64(buffer, index, count); // turn on bInReadBinary in again and return _bInReadBinary = true; @@ -1826,7 +1838,7 @@ namespace System.Xml _bInReadBinary = false; // call to the helper - int readCount = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count); + int readCount = _readBinaryHelper!.ReadContentAsBinHex(buffer, index, count); // turn on bInReadBinary in again and return _bInReadBinary = true; @@ -1850,7 +1862,7 @@ namespace System.Xml _bInReadBinary = false; // call to the helper - int readCount = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count); + int readCount = _readBinaryHelper!.ReadElementContentAsBase64(buffer, index, count); // turn on bInReadBinary in again and return _bInReadBinary = true; @@ -1874,7 +1886,7 @@ namespace System.Xml _bInReadBinary = false; // call to the helper - int readCount = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count); + int readCount = _readBinaryHelper!.ReadElementContentAsBinHex(buffer, index, count); // turn on bInReadBinary in again and return _bInReadBinary = true; @@ -1884,7 +1896,7 @@ namespace System.Xml private void FinishReadBinary() { _bInReadBinary = false; - _readBinaryHelper.Finish(); + _readBinaryHelper!.Finish(); } // @@ -1896,27 +1908,29 @@ namespace System.Xml return _readerNav.GetNamespacesInScope(scope); } - string IXmlNamespaceResolver.LookupPrefix(string namespaceName) + string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _readerNav.LookupPrefix(namespaceName); } - string IXmlNamespaceResolver.LookupNamespace(string prefix) + string? IXmlNamespaceResolver.LookupNamespace(string prefix) { if (!IsInReadingStates()) { return _readerNav.DefaultLookupNamespace(prefix); } - string ns = _readerNav.LookupNamespace(prefix); + + string? ns = _readerNav.LookupNamespace(prefix); if (ns != null) { ns = _readerNav.NameTable.Add(ns); } + return ns; } // DTD/Schema info used by XmlReader.GetDtdSchemaInfo() - internal override IDtdInfo DtdInfo + internal override IDtdInfo? DtdInfo { get { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNotation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNotation.cs index ed7d107..79ed84c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNotation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNotation.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { using System; @@ -9,11 +10,11 @@ namespace System.Xml // Contains a notation declared in the DTD or schema. public class XmlNotation : XmlNode { - private readonly string _publicId; - private readonly string _systemId; + private readonly string? _publicId; + private readonly string? _systemId; private readonly string _name; - internal XmlNotation(string name, string publicId, string systemId, XmlDocument doc) : base(doc) + internal XmlNotation(string name, string? publicId, string? systemId, XmlDocument doc) : base(doc) { _name = doc.NameTable.Add(name); _publicId = publicId; @@ -58,14 +59,14 @@ namespace System.Xml } // Gets the value of the public identifier on the notation declaration. - public string PublicId + public string? PublicId { get { return _publicId; } } // Gets the value of // the system identifier on the notation declaration. - public string SystemId + public string? SystemId { get { return _systemId; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs index 6fc679f..89e36be 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs @@ -1,7 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Xml.XPath; namespace System.Xml @@ -37,14 +39,15 @@ namespace System.Xml } // Gets or sets the value of the node. + [AllowNull] public override string Value { get { return _data; } - set { Data = value; } //use Data instead of data so that event will be fired + set { Data = value!; } //use Data instead of data so that event will be fired } // Gets the target of the processing instruction. - public string Target + public string? Target { get { return _target; } } @@ -56,8 +59,8 @@ namespace System.Xml get { return _data; } set { - XmlNode parent = ParentNode; - XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, value, XmlNodeChangedAction.Change); + XmlNode? parent = ParentNode; + XmlNodeChangedEventArgs? args = GetEventArgs(this, parent, parent, _data, value, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); _data = value; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs index a7ba3c8..dd9995d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; using System.Xml.XPath; @@ -9,7 +10,7 @@ namespace System.Xml // Represents the text content of an element or attribute. public class XmlSignificantWhitespace : XmlCharacterData { - protected internal XmlSignificantWhitespace(string strData, XmlDocument doc) : base(strData, doc) + protected internal XmlSignificantWhitespace(string? strData, XmlDocument doc) : base(strData, doc) { if (!doc.IsLoading && !base.CheckOnData(strData)) throw new ArgumentException(SR.Xdom_WS_Char); @@ -20,7 +21,7 @@ namespace System.Xml { get { - return OwnerDocument.strSignificantWhitespaceName; + return OwnerDocument!.strSignificantWhitespaceName; } } @@ -29,7 +30,7 @@ namespace System.Xml { get { - return OwnerDocument.strSignificantWhitespaceName; + return OwnerDocument!.strSignificantWhitespaceName; } } @@ -42,11 +43,11 @@ namespace System.Xml } } - public override XmlNode ParentNode + public override XmlNode? ParentNode { get { - switch (parentNode.NodeType) + switch (parentNode!.NodeType) { case XmlNodeType.Document: return base.ParentNode; @@ -54,10 +55,10 @@ namespace System.Xml case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: - XmlNode parent = parentNode.parentNode; + XmlNode parent = parentNode.parentNode!; while (parent.IsText) { - parent = parent.parentNode; + parent = parent.parentNode!; } return parent; default: @@ -73,7 +74,7 @@ namespace System.Xml return OwnerDocument.CreateSignificantWhitespace(Data); } - public override string Value + public override string? Value { get { @@ -119,14 +120,15 @@ namespace System.Xml } } - public override XmlNode PreviousText + public override XmlNode? PreviousText { get { - if (parentNode.IsText) + if (parentNode != null && parentNode.IsText) { return parentNode; } + return null; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs index 9a0bf27..db45335 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs @@ -1,7 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Xml.XPath; namespace System.Xml @@ -9,11 +11,11 @@ namespace System.Xml // Represents the text content of an element or attribute. public class XmlText : XmlCharacterData { - internal XmlText(string strData) : this(strData, null) + internal XmlText(string? strData) : this(strData, null!) // always throws ArgumentNullException { } - protected internal XmlText(string strData, XmlDocument doc) : base(strData, doc) + protected internal XmlText(string? strData, XmlDocument doc) : base(strData, doc) { } @@ -22,7 +24,7 @@ namespace System.Xml { get { - return OwnerDocument.strTextName; + return OwnerDocument!.strTextName; } } @@ -31,7 +33,7 @@ namespace System.Xml { get { - return OwnerDocument.strTextName; + return OwnerDocument!.strTextName; } } @@ -44,11 +46,11 @@ namespace System.Xml } } - public override XmlNode ParentNode + public override XmlNode? ParentNode { get { - switch (parentNode.NodeType) + switch (parentNode!.NodeType) { case XmlNodeType.Document: return null; @@ -56,11 +58,12 @@ namespace System.Xml case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: - XmlNode parent = parentNode.parentNode; + XmlNode parent = parentNode.parentNode!; while (parent.IsText) { - parent = parent.parentNode; + parent = parent.parentNode!; } + return parent; default: return parentNode; @@ -75,7 +78,7 @@ namespace System.Xml return OwnerDocument.CreateTextNode(Data); } - public override string Value + public override string? Value { get { @@ -85,10 +88,10 @@ namespace System.Xml set { Data = value; - XmlNode parent = parentNode; + XmlNode? parent = parentNode; if (parent != null && parent.NodeType == XmlNodeType.Attribute) { - XmlUnspecifiedAttribute attr = parent as XmlUnspecifiedAttribute; + XmlUnspecifiedAttribute? attr = parent as XmlUnspecifiedAttribute; if (attr != null && !attr.Specified) { attr.SetSpecified(true); @@ -101,7 +104,7 @@ namespace System.Xml // both in the tree as siblings. public virtual XmlText SplitText(int offset) { - XmlNode parentNode = this.ParentNode; + XmlNode? parentNode = this.ParentNode; int length = this.Length; if (offset > length) throw new ArgumentOutOfRangeException(nameof(offset)); @@ -112,7 +115,7 @@ namespace System.Xml int count = length - offset; string splitData = Substring(offset, count); DeleteData(offset, count); - XmlText newTextNode = OwnerDocument.CreateTextNode(splitData); + XmlText newTextNode = OwnerDocument!.CreateTextNode(splitData); parentNode.InsertAfter(newTextNode, this); return newTextNode; } @@ -145,14 +148,15 @@ namespace System.Xml } } - public override XmlNode PreviousText + public override XmlNode? PreviousText { get { - if (parentNode.IsText) + if (parentNode != null && parentNode.IsText) { return parentNode; } + return null; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlUnspecifiedAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlUnspecifiedAttribute.cs index 07e8f9f..205d1d8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlUnspecifiedAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlUnspecifiedAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml { internal class XmlUnspecifiedAttribute : XmlAttribute @@ -8,7 +9,7 @@ namespace System.Xml private bool _fSpecified; - protected internal XmlUnspecifiedAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc) + protected internal XmlUnspecifiedAttribute(string? prefix, string localName, string? namespaceURI, XmlDocument doc) : base(prefix, localName, namespaceURI, doc) { } @@ -38,16 +39,16 @@ namespace System.Xml } } - public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) + public override XmlNode? InsertBefore(XmlNode newChild, XmlNode? refChild) { - XmlNode node = base.InsertBefore(newChild, refChild); + XmlNode? node = base.InsertBefore(newChild, refChild); _fSpecified = true; return node; } - public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) + public override XmlNode? InsertAfter(XmlNode newChild, XmlNode? refChild) { - XmlNode node = base.InsertAfter(newChild, refChild); + XmlNode? node = base.InsertAfter(newChild, refChild); _fSpecified = true; return node; } @@ -66,9 +67,9 @@ namespace System.Xml return node; } - public override XmlNode AppendChild(XmlNode newChild) + public override XmlNode? AppendChild(XmlNode newChild) { - XmlNode node = base.AppendChild(newChild); + XmlNode? node = base.AppendChild(newChild); _fSpecified = true; return node; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs index ecdcd91..7f9509c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs @@ -1,7 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Xml.XPath; namespace System.Xml @@ -9,7 +11,7 @@ namespace System.Xml // Represents the text content of an element or attribute. public class XmlWhitespace : XmlCharacterData { - protected internal XmlWhitespace(string strData, XmlDocument doc) : base(strData, doc) + protected internal XmlWhitespace(string? strData, XmlDocument doc) : base(strData, doc) { if (!doc.IsLoading && !base.CheckOnData(strData)) throw new ArgumentException(SR.Xdom_WS_Char); @@ -20,7 +22,7 @@ namespace System.Xml { get { - return OwnerDocument.strNonSignificantWhitespaceName; + return OwnerDocument!.strNonSignificantWhitespaceName; } } @@ -29,7 +31,7 @@ namespace System.Xml { get { - return OwnerDocument.strNonSignificantWhitespaceName; + return OwnerDocument!.strNonSignificantWhitespaceName; } } @@ -42,11 +44,11 @@ namespace System.Xml } } - public override XmlNode ParentNode + public override XmlNode? ParentNode { get { - switch (parentNode.NodeType) + switch (parentNode!.NodeType) { case XmlNodeType.Document: return base.ParentNode; @@ -54,10 +56,10 @@ namespace System.Xml case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: - XmlNode parent = parentNode.parentNode; + XmlNode parent = parentNode.parentNode!; while (parent.IsText) { - parent = parent.parentNode; + parent = parent.parentNode!; } return parent; default: @@ -66,13 +68,12 @@ namespace System.Xml } } - public override string Value + public override string? Value { get { return Data; } - set { if (CheckOnData(value)) @@ -119,14 +120,15 @@ namespace System.Xml } } - public override XmlNode PreviousText + public override XmlNode? PreviousText { get { - if (parentNode.IsText) + if (parentNode != null && parentNode.IsText) { return parentNode; } + return null; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs index d5cf08b..e09c29c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.IO; using System.Xml; using System.Net; @@ -34,15 +35,16 @@ namespace System.Xml.Resolvers } // Returns true for types that are supported for this preloaded data; Stream must always be supported - internal virtual bool SupportsType(Type type) + internal virtual bool SupportsType(Type? type) { if (type == null || type == typeof(Stream)) { return true; } + return false; } - }; + } // // XmlKnownDtdData class @@ -63,7 +65,7 @@ namespace System.Xml.Resolvers internal override Stream AsStream() { Assembly asm = GetType().Assembly; - return asm.GetManifestResourceStream(_resourceName); + return asm.GetManifestResourceStream(_resourceName)!; } } @@ -110,12 +112,13 @@ namespace System.Xml.Resolvers return new StringReader(_str); } - internal override bool SupportsType(Type type) + internal override bool SupportsType(Type? type) { if (type == typeof(TextReader)) { return true; } + return base.SupportsType(type); } } @@ -123,7 +126,7 @@ namespace System.Xml.Resolvers // // Fields // - private readonly XmlResolver _fallbackResolver; + private readonly XmlResolver? _fallbackResolver; private readonly Dictionary _mappings; private readonly XmlKnownDtds _preloadedDtds; @@ -156,17 +159,17 @@ namespace System.Xml.Resolvers { } - public XmlPreloadedResolver(XmlResolver fallbackResolver) + public XmlPreloadedResolver(XmlResolver? fallbackResolver) : this(fallbackResolver, XmlKnownDtds.All, null) { } - public XmlPreloadedResolver(XmlResolver fallbackResolver, XmlKnownDtds preloadedDtds) + public XmlPreloadedResolver(XmlResolver? fallbackResolver, XmlKnownDtds preloadedDtds) : this(fallbackResolver, preloadedDtds, null) { } - public XmlPreloadedResolver(XmlResolver fallbackResolver, XmlKnownDtds preloadedDtds, IEqualityComparer uriComparer) + public XmlPreloadedResolver(XmlResolver? fallbackResolver, XmlKnownDtds preloadedDtds, IEqualityComparer? uriComparer) { _fallbackResolver = fallbackResolver; _mappings = new Dictionary(16, uriComparer); @@ -186,7 +189,7 @@ namespace System.Xml.Resolvers } } - public override Uri ResolveUri(Uri baseUri, string relativeUri) + public override Uri ResolveUri(Uri? baseUri, string? relativeUri) { // 1) special-case well-known public IDs // 2) To make FxCop happy we need to use StartsWith() overload that takes StringComparison -> @@ -216,23 +219,25 @@ namespace System.Xml.Resolvers } } } + return base.ResolveUri(baseUri, relativeUri); } - public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) + public override object? GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn) { if (absoluteUri == null) { throw new ArgumentNullException(nameof(absoluteUri)); } - PreloadedData data; + PreloadedData? data; if (!_mappings.TryGetValue(absoluteUri, out data)) { if (_fallbackResolver != null) { return _fallbackResolver.GetEntity(absoluteUri, role, ofObjectToReturn); } + throw new XmlException(SR.Format(SR.Xml_CannotResolveUrl, absoluteUri)); } @@ -261,14 +266,14 @@ namespace System.Xml.Resolvers } } - public override bool SupportsType(Uri absoluteUri, Type type) + public override bool SupportsType(Uri absoluteUri, Type? type) { if (absoluteUri == null) { throw new ArgumentNullException(nameof(absoluteUri)); } - PreloadedData data; + PreloadedData? data; if (!_mappings.TryGetValue(absoluteUri, out data)) { if (_fallbackResolver != null) @@ -291,6 +296,7 @@ namespace System.Xml.Resolvers { throw new ArgumentNullException(nameof(value)); } + Add(uri, new ByteArrayChunk(value, 0, value.Length)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseValidator.cs index b6b2a59..17a51af 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseValidator.cs @@ -16,7 +16,7 @@ namespace System.Xml.Schema internal class BaseValidator { private readonly XmlSchemaCollection? _schemaCollection; - private readonly IValidationEventHandling _eventHandling; + private readonly IValidationEventHandling? _eventHandling; private readonly XmlNameTable _nameTable; private SchemaNames? _schemaNames; private readonly PositionInfo _positionInfo; @@ -45,7 +45,7 @@ namespace System.Xml.Schema elementName = other.elementName; } - public BaseValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection? schemaCollection, IValidationEventHandling eventHandling) + public BaseValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection? schemaCollection, IValidationEventHandling? eventHandling) { Debug.Assert(schemaCollection == null || schemaCollection.NameTable == reader.NameTable); this.reader = reader; @@ -110,9 +110,9 @@ namespace System.Xml.Schema set { _baseUri = value; } } - public ValidationEventHandler EventHandler + public ValidationEventHandler? EventHandler { - get { return (ValidationEventHandler)_eventHandling.EventHandler; } + get { return (ValidationEventHandler?)_eventHandling!.EventHandler; } } public SchemaInfo? SchemaInfo diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs index f83c30d..ba85152 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs @@ -269,7 +269,7 @@ namespace System.Xml _freeFloatingDtd = false; } - private void InitializeFreeFloatingDtd(string baseUri, string docTypeName, string publicId, string systemId, string internalSubset, IDtdParserAdapter adapter) + private void InitializeFreeFloatingDtd(string baseUri, string docTypeName, string? publicId, string? systemId, string? internalSubset, IDtdParserAdapter adapter) { Initialize(adapter); @@ -340,7 +340,7 @@ namespace System.Xml return _schemaInfo; } - IDtdInfo IDtdParser.ParseFreeFloatingDtd(string baseUri, string docTypeName, string publicId, string systemId, string internalSubset, IDtdParserAdapter adapter) + IDtdInfo IDtdParser.ParseFreeFloatingDtd(string baseUri, string docTypeName, string? publicId, string? systemId, string? internalSubset, IDtdParserAdapter adapter) { InitializeFreeFloatingDtd(baseUri, docTypeName, publicId, systemId, internalSubset, adapter); Parse(false); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs index f725bad..a385ee2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs @@ -566,7 +566,7 @@ namespace System.Xml.Schema SchemaAttDef attdef, SchemaInfo sinfo, IValidationEventHandling eventHandling, - string baseUriStr + string? baseUriStr ) { try diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs index a70e1e3..967afd5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs @@ -247,13 +247,14 @@ namespace System.Xml.Schema XmlNode[] markup = new XmlNode[list.Count]; for (int i = 0; i < list.Count; i++) { - markup[i] = list[i]; + markup[i] = list[i]!; } _builder!.ProcessMarkup(markup); _namespaceManager!.PopScope(); _builder.EndChildren(); } + _markupDepth = int.MaxValue; } else @@ -405,7 +406,7 @@ namespace System.Xml.Schema XmlAttribute attr; if (prefix.Length == 0) { - attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns, XmlReservedNs.NsXmlNs); + attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns!, XmlReservedNs.NsXmlNs); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs index b9f8875..a5df534 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs @@ -31,7 +31,7 @@ namespace System.Xml.Schema Init(); } - internal XdrValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection schemaCollection, IValidationEventHandling eventHandling) : base(reader, schemaCollection, eventHandling) + internal XdrValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection schemaCollection, IValidationEventHandling? eventHandling) : base(reader, schemaCollection, eventHandling) { Init(); } @@ -42,7 +42,7 @@ namespace System.Xml.Schema [MemberNotNull(nameof(_attPresence))] private void Init() { - _nsManager = reader.NamespaceManager; + _nsManager = reader.NamespaceManager!; if (_nsManager == null) { _nsManager = new XmlNamespaceManager(NameTable); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs index 0c6aeac..707de03 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs @@ -83,7 +83,7 @@ namespace System.Xml.Schema remove { _validationEventHandler -= value; } } - internal XmlResolver XmlResolver + internal XmlResolver? XmlResolver { set { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidationException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidationException.cs index fccacd3..993aa85 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidationException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidationException.cs @@ -69,7 +69,7 @@ namespace System.Xml.Schema get { return _sourceNodeObject; } } - protected internal void SetSourceObject(object sourceObject) + protected internal void SetSourceObject(object? sourceObject) { _sourceNodeObject = sourceObject; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index 386f0a2..5b993c8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -17,7 +17,7 @@ using System.Diagnostics.CodeAnalysis; namespace System.Xml.Schema { - public delegate object XmlValueGetter(); + public delegate object? XmlValueGetter(); [Flags] public enum XmlSchemaValidationFlags @@ -677,7 +677,7 @@ namespace System.Xml.Schema object attValue; if (attributeValueGetter != null) { - attValue = attributeValueGetter(); + attValue = attributeValueGetter()!; } else { @@ -821,7 +821,7 @@ namespace System.Xml.Schema case XmlSchemaContentType.TextOnly: if (elementValueGetter != null) { - SaveTextValue(elementValueGetter()); + SaveTextValue(elementValueGetter()!); } else { @@ -830,7 +830,7 @@ namespace System.Xml.Schema break; case XmlSchemaContentType.ElementOnly: - string textValue = elementValueGetter != null ? elementValueGetter().ToString()! : elementStringValue!; + string textValue = elementValueGetter != null ? elementValueGetter()!.ToString()! : elementStringValue!; if (_xmlCharType.IsOnlyWhitespace(textValue)) { break; @@ -852,7 +852,7 @@ namespace System.Xml.Schema { if (elementValueGetter != null) { - SaveTextValue(elementValueGetter()); + SaveTextValue(elementValueGetter()!); } else { @@ -905,7 +905,7 @@ namespace System.Xml.Schema case XmlSchemaContentType.TextOnly: if (elementValueGetter != null) { - SaveTextValue(elementValueGetter()); + SaveTextValue(elementValueGetter()!); } else { @@ -918,7 +918,7 @@ namespace System.Xml.Schema { if (elementValueGetter != null) { - SaveTextValue(elementValueGetter()); + SaveTextValue(elementValueGetter()!); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs index 241a501..2191857 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs @@ -68,12 +68,13 @@ namespace System.Xml.Schema [MemberNotNull(nameof(_xsdSchema))] private void Init() { - _nsManager = reader.NamespaceManager; + _nsManager = reader.NamespaceManager!; if (_nsManager == null) { _nsManager = new XmlNamespaceManager(NameTable); _bManageNamespaces = true; } + _validationStack = new HWStack(STACK_INCREMENT); textValue = new StringBuilder(); _attPresence = new Hashtable(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs index 9498b6a..82cfb9d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs @@ -203,13 +203,13 @@ namespace System.Xml highChar = (char)(SurHighStart + v / 1024); } - internal bool IsOnlyWhitespace(string str) + internal bool IsOnlyWhitespace(string? str) { return IsOnlyWhitespaceWithPos(str) == -1; } // Character checking on strings - internal int IsOnlyWhitespaceWithPos(string str) + internal int IsOnlyWhitespaceWithPos(string? str) { if (str != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs index f777c49..83268d4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -1474,12 +1474,12 @@ namespace System.Xml return *((long*)&value); } - internal static void VerifyCharData(string data, ExceptionType exceptionType) + internal static void VerifyCharData(string? data, ExceptionType exceptionType) { VerifyCharData(data, exceptionType, exceptionType); } - internal static void VerifyCharData(string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType) + internal static void VerifyCharData(string? data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType) { if (data == null || data.Length == 0) {