}
}
- public override string? GetAttribute(string name, string ns)
+ public override string? GetAttribute(string name, string? ns)
{
if (ScanState.XmlText == _state)
{
}
}
- public override bool MoveToAttribute(string name, string ns)
+ public override bool MoveToAttribute(string name, string? ns)
{
if (ScanState.XmlText == _state)
{
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);
}
}
/// </summary>
internal interface IRemovableWriter
{
- OnRemoveWriter OnRemoveWriterEvent { get; set; }
+ OnRemoveWriter? OnRemoveWriterEvent { get; set; }
}
}
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);
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)
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)
{
// 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.Diagnostics;
using System.Globalization;
+using System.Diagnostics.CodeAnalysis;
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;
_nameWPrefix = nameTable.Add(string.Concat(_prefix, ":", _localName));
}
}
+
return _nameWPrefix;
}
}
}
- public string OriginalStringValue
+ public string? OriginalStringValue
{
get
{
}
}
- public AttributePSVIInfo AttInfo
+ public AttributePSVIInfo? AttInfo
{
get
{
}
}
+ [MemberNotNull(nameof(_localName))]
+ [MemberNotNull(nameof(_prefix))]
+ [MemberNotNull(nameof(_namespaceUri))]
+ [MemberNotNull(nameof(_rawValue))]
internal void Clear(XmlNodeType nodeType)
{
_nodeType = nodeType;
_prefix = string.Empty;
_namespaceUri = string.Empty;
_rawValue = string.Empty;
+
if (_attributePSVIInfo != null)
{
_attributePSVIInfo.Reset();
}
+
_nameWPrefix = null;
_lineNo = 0;
_linePos = 0;
_linePos = linePos;
}
- internal void SetLineInfo(IXmlLineInfo lineInfo)
+ internal void SetLineInfo(IXmlLineInfo? lineInfo)
{
if (lineInfo != null)
{
SetItemData(value, value);
}
- internal void SetItemData(string value, string originalStringValue)
+ internal void SetItemData(string value, string? originalStringValue)
{
_rawValue = value;
_originalStringValue = originalStringValue;
// 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;
{
get
{
- XmlReaderSettings settings = _coreReader.Settings;
+ XmlReaderSettings? settings = _coreReader.Settings;
if (null != settings)
{
settings = settings.Clone();
}
}
- public override string BaseURI
+ public override string? BaseURI
{
get
{
}
}
- public override IXmlSchemaInfo SchemaInfo
+ public override IXmlSchemaInfo? SchemaInfo
{
get
{
}
}
- 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);
}
}
- public override string this[string name]
+ public override string? this[string name]
{
get
{
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);
}
}
- public override string LookupNamespace(string prefix)
+ public override string? LookupNamespace(string prefix)
{
CheckAsync();
return _coreReader.LookupNamespace(prefix);
_coreReader.Dispose();
}
- internal override XmlNamespaceManager NamespaceManager
+ internal override XmlNamespaceManager? NamespaceManager
{
get
{
}
}
- internal override IDtdInfo DtdInfo
+ internal override IDtdInfo? DtdInfo
{
get
{
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);
}
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);
}
_readerAsIXmlSchemaInfo = (IXmlSchemaInfo)reader;
}
-
#region IXmlSchemaInfo members
XmlSchemaValidity IXmlSchemaInfo.Validity
}
}
- XmlSchemaSimpleType IXmlSchemaInfo.MemberType
+ XmlSchemaSimpleType? IXmlSchemaInfo.MemberType
{
get
{
}
}
- XmlSchemaType IXmlSchemaInfo.SchemaType
+ XmlSchemaType? IXmlSchemaInfo.SchemaType
{
get
{
}
}
- XmlSchemaElement IXmlSchemaInfo.SchemaElement
+ XmlSchemaElement? IXmlSchemaInfo.SchemaElement
{
get
{
}
}
- XmlSchemaAttribute IXmlSchemaInfo.SchemaAttribute
+ XmlSchemaAttribute? IXmlSchemaInfo.SchemaAttribute
{
get
{
// 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;
{
get
{
- XmlWriterSettings settings = _coreWriter.Settings;
+ XmlWriterSettings? settings = _coreWriter.Settings;
if (null != settings)
{
_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);
_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);
_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);
_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);
_coreWriter.Flush();
}
- public override string LookupPrefix(string ns)
+ public override string? LookupPrefix(string ns)
{
CheckAsync();
return _coreWriter.LookupPrefix(ns);
}
}
- public override string XmlLang
+ public override string? XmlLang
{
get
{
_coreWriter.WriteName(name);
}
- public override void WriteQualifiedName(string localName, string ns)
+ public override void WriteQualifiedName(string localName, string? ns)
{
CheckAsync();
_coreWriter.WriteQualifiedName(localName, ns);
_coreWriter.WriteValue(value);
}
- public override void WriteValue(string value)
+ public override void WriteValue(string? value)
{
CheckAsync();
_coreWriter.WriteValue(value);
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);
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);
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);
return task;
}
- public override Task WriteCDataAsync(string text)
+ public override Task WriteCDataAsync(string? text)
{
CheckAsync();
var task = _coreWriter.WriteCDataAsync(text);
return task;
}
- public override Task WriteCommentAsync(string text)
+ public override Task WriteCommentAsync(string? text)
{
CheckAsync();
var task = _coreWriter.WriteCommentAsync(text);
return task;
}
- public override Task WriteWhitespaceAsync(string ws)
+ public override Task WriteWhitespaceAsync(string? ws)
{
CheckAsync();
var task = _coreWriter.WriteWhitespaceAsync(ws);
return task;
}
- public override Task WriteStringAsync(string text)
+ public override Task WriteStringAsync(string? text)
{
CheckAsync();
var task = _coreWriter.WriteStringAsync(text);
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);
// 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;
/// </summary>
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
/// <summary>
/// This writer will raise this event once it has determined whether to replace itself with the Html or Xml writer.
/// </summary>
- public OnRemoveWriter OnRemoveWriterEvent
+ public OnRemoveWriter? OnRemoveWriterEvent
{
get { return _onRemove; }
set { _onRemove = value; }
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);
_wrapped.WriteEndAttribute();
}
- public override void WriteCData(string text)
+ public override void WriteCData(string? text)
{
if (TextBlockCreatesWriter(text))
_wrapped.WriteCData(text);
_eventCache.WriteCData(text);
}
- public override void WriteComment(string text)
+ public override void WriteComment(string? text)
{
if (_wrapped == null)
_eventCache.WriteComment(text);
_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);
_wrapped.WriteProcessingInstruction(name, text);
}
- public override void WriteWhitespace(string ws)
+ public override void WriteWhitespace(string? ws)
{
if (_wrapped == null)
_eventCache.WriteWhitespace(ws);
_wrapped.WriteWhitespace(ws);
}
- public override void WriteString(string text)
+ public override void WriteString(string? text)
{
if (TextBlockCreatesWriter(text))
_wrapped.WriteString(text);
_wrapped.WriteValue(value);
}
- public override void WriteValue(string value)
+ public override void WriteValue(string? value)
{
EnsureWrappedWriter(XmlOutputMethod.Xml);
_wrapped.WriteValue(value);
// XmlRawWriter interface
//-----------------------------------------------
- internal override IXmlNamespaceResolver NamespaceResolver
+ internal override IXmlNamespaceResolver? NamespaceResolver
{
get
{
{
get
{
- return _wrapped.SupportsNamespaceDeclarationInChunks;
+ return _wrapped!.SupportsNamespaceDeclarationInChunks;
}
}
internal override void WriteEndNamespaceDeclaration()
{
- _wrapped.WriteEndNamespaceDeclaration();
+ _wrapped!.WriteEndNamespaceDeclaration();
}
//-----------------------------------------------
/// <summary>
/// If a wrapped writer has not yet been created, create one.
/// </summary>
+ [MemberNotNull(nameof(_wrapped))]
private void EnsureWrappedWriter(XmlOutputMethod outMethod)
{
if (_wrapped == null)
/// force the creation of a wrapped writer. Otherwise, create a wrapped writer if one has not yet been
/// created and return true.
/// </summary>
- private bool TextBlockCreatesWriter(string textBlock)
+ [MemberNotNullWhen(true, nameof(_wrapped))]
+ private bool TextBlockCreatesWriter(string? textBlock)
{
if (_wrapped == null)
{
/// <summary>
/// Create either the Html or Xml writer and send any cached events to it.
/// </summary>
+ [MemberNotNull(nameof(_wrapped))]
private void CreateWrappedWriter(XmlOutputMethod outMethod)
{
Debug.Assert(_wrapped == null);
_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();
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)
{
// 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;
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);
// 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
{
{
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)
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)
{
{
throw new ArgumentException(SR.Xml_EmptyLocalName);
}
+
ValidateNCName(localName);
if (prefix != null && prefix.Length > 0)
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)
{
{
throw new ArgumentException(SR.Xml_EmptyLocalName);
}
+
ValidateNCName(localName);
if (prefix != null && prefix.Length > 0)
ValidateNCName(prefix);
}
}
+
writer.WriteStartAttribute(prefix, localName, ns);
}
- public override void WriteCData(string text)
+ public override void WriteCData(string? text)
{
if (text != null)
{
{
CheckCharacters(text);
}
+
if (_replaceNewLines)
{
text = ReplaceNewLines(text);
}
+
int i;
while ((i = text.IndexOf("]]>", StringComparison.Ordinal)) >= 0)
{
writer.WriteCData(text);
}
- public override void WriteComment(string text)
+ public override void WriteComment(string? text)
{
if (text != null)
{
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)
CheckCharacters(text);
text = InterleaveInvalidChars(text, '?', '>');
}
+
if (_replaceNewLines)
{
text = ReplaceNewLines(text);
}
}
+
writer.WriteProcessingInstruction(name, text);
}
{
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)
{
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)
{
text = ReplaceNewLines(text);
}
}
+
writer.WriteString(text);
}
{
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);
}
{
throw new ArgumentException(SR.Xml_EmptyName);
}
+
XmlConvert.VerifyNMTOKEN(name);
}
+
writer.WriteNmToken(name);
}
{
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);
}
{
throw new ArgumentException(SR.Xml_EmptyName);
}
+
int colonPos;
int len = ValidateNames.ParseQName(name, 0, out colonPos);
if (len != name.Length)
}
}
- 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++)
i++;
continue;
}
+
if (sb == null)
{
sb = new StringBuilder(str.Length + 5);
}
+
sb.Append(str, start, i - start);
i++;
}
{
continue;
}
+
if (sb == null)
{
sb = new StringBuilder(str.Length + 5);
}
+
sb.Append(str, start, i - start);
}
}
}
}
- 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;
{
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')
i++;
continue;
}
+
if (sb == null)
{
sb = new StringBuilder(len + 5);
}
+
sb.Append(data, start, i - start);
i++;
}
{
continue;
}
+
if (sb == null)
{
sb = new StringBuilder(len + 5);
}
+
sb.Append(data, start, i - start);
}
}
{
continue;
}
+
sb.Append(_newLineChars);
start = i + 1;
}
// 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++)
{
sb = new StringBuilder(text.Length + 5);
}
+
sb.Append(text, start, i - start);
sb.Append(' ');
start = i;
{
sb.Append(' ');
}
+
return sb.ToString();
}
}
// 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;
//
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)
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)
{
{
throw new ArgumentException(SR.Xml_EmptyLocalName);
}
+
ValidateNCName(localName);
if (prefix != null && prefix.Length > 0)
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)
{
{
throw new ArgumentException(SR.Xml_EmptyLocalName);
}
+
ValidateNCName(localName);
if (prefix != null && prefix.Length > 0)
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)
{
{
CheckCharacters(text);
}
+
if (_replaceNewLines)
{
text = ReplaceNewLines(text);
}
+
int i;
while ((i = text.IndexOf("]]>", StringComparison.Ordinal)) >= 0)
{
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)
{
{
ValidateNCName(name);
}
+
if (text != null)
{
if (_checkValues)
text = ReplaceNewLines(text);
}
}
- return writer.WriteProcessingInstructionAsync(name, text);
+
+ return writer.WriteProcessingInstructionAsync(name, text!);
}
public override Task WriteEntityRefAsync(string name)
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)
{
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)
{
{
CheckCharacters(text);
}
+
if (_replaceNewLines && WriteState != WriteState.Attribute)
{
text = ReplaceNewLines(text);
}
}
+
return writer.WriteStringAsync(text);
}
{
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);
}
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);
}
}
}
// Forward call to WriteString(string).
- public override Task WriteCDataAsync(string text)
+ public override Task WriteCDataAsync(string? text)
{
return WriteStringAsync(text);
}
}
// Forward call to WriteString(string).
- public override Task WriteWhitespaceAsync(string ws)
+ public override Task WriteWhitespaceAsync(string? ws)
{
return WriteStringAsync(ws);
}
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);
}
// 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
{
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)
return null;
}
- public override string? GetAttribute(string name, string namespaceURI)
+ public override string? GetAttribute(string name, string? namespaceURI)
{
if (!InAttributeActiveState)
{
return false;
}
- public override bool MoveToAttribute(string name, string ns)
+ public override bool MoveToAttribute(string name, string? ns)
{
if (!InAttributeActiveState)
{
_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;
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);
}
// 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;
// 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)
// "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("<?xml ", xmlFragment, "?>"));
// 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);
// Validation support
//
- internal IValidationEventHandling ValidationEventHandling
+ internal IValidationEventHandling? ValidationEventHandling
{
set
{
}
// 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)
{
// 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;
// Member fields
//
private readonly XmlValidatingReaderImpl _impl;
+
//
// Constructors
//
{
throw new ArgumentNullException(nameof(xmlFragment));
}
+
_impl = new XmlValidatingReaderImpl(xmlFragment, fragType, context);
_impl.OuterReader = this;
}
get { return _impl.Depth; }
}
- public override string BaseURI
+ public override string? BaseURI
{
get { return _impl.BaseURI; }
}
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);
}
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);
}
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;
}
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);
}
remove { _impl.ValidationEventHandler -= value; }
}
- public object SchemaType
+ public object? SchemaType
{
get { return _impl.SchemaType; }
}
set { _impl.Namespaces = value; }
}
- public object ReadTypedValue()
+ public object? ReadTypedValue()
{
return _impl.ReadTypedValue();
}
- public Encoding Encoding
+ public Encoding? Encoding
{
get { return _impl.Encoding; }
}
get { return _impl; }
}
- internal override IDtdInfo DtdInfo
+ internal override IDtdInfo? DtdInfo
{
get { return _impl.DtdInfo; }
}
// 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.Globalization;
using System.Collections.Generic;
using System.Runtime.Versioning;
+using System.Diagnostics.CodeAnalysis;
namespace System.Xml
{
{
// Fields
private readonly XmlValidatingReaderImpl _reader;
- private ValidationEventHandler _eventHandler;
+ private ValidationEventHandler? _eventHandler;
// Constructor
internal ValidationEventHandling(XmlValidatingReaderImpl reader)
// IValidationEventHandling interface
#region IValidationEventHandling interface
- object IValidationEventHandling.EventHandler
+ object? IValidationEventHandling.EventHandler
{
get { return _eventHandler; }
}
// core text reader
private readonly XmlReader _coreReader;
private readonly XmlTextReaderImpl _coreReaderImpl;
- private readonly IXmlNamespaceResolver _coreReaderNSResolver;
+ private readonly IXmlNamespaceResolver? _coreReaderNSResolver;
// validation
private ValidationType _validationType;
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
// 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;
_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)
// 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)
// 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;
// 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;
{
settings = _coreReader.Settings;
}
+
if (settings != null)
{
settings = settings.Clone();
{
settings = new XmlReaderSettings();
}
+
settings.ValidationType = ValidationType.DTD;
if (!_processIdentityConstraints)
{
settings.ValidationFlags &= ~XmlSchemaValidationFlags.ProcessIdentityConstraints;
}
+
settings.ReadOnly = true;
return settings;
}
}
// Returns the base URI of the current node.
- public override string BaseURI
+ public override string? BaseURI
{
get
{
}
// Returns encoding of the XML document
- internal Encoding Encoding
+ internal Encoding? Encoding
{
get
{
}
// 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);
}
}
// 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))
{
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}");
}
// 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);
}
if (_parsingFunction == ParsingFunction.InReadBinaryContent)
{
_parsingFunction = ParsingFunction.Read;
- _readBinaryHelper.Finish();
+ _readBinaryHelper!.Finish();
}
if (!_coreReader.ReadAttributeValue())
{
_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;
_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;
_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;
_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;
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);
}
// Internal IXmlNamespaceResolver methods
internal IDictionary<string, string> 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);
}
//
}
// 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
}
// Returns typed value of the current node (based on the type specified by schema)
- public object ReadTypedValue()
+ public object? ReadTypedValue()
{
if (_validationType == ValidationType.None)
{
{
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)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
+
XmlNodeType type = _outerReader.NodeType;
if (type != XmlNodeType.CDATA && type != XmlNodeType.Text &&
type != XmlNodeType.Whitespace && type != XmlNodeType.SignificantWhitespace &&
break;
}
}
+
if (_outerReader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _outerReader.NodeType.ToString());
private void ValidateDtd()
{
- IDtdInfo dtdInfo = _coreReaderImpl.DtdInfo;
+ IDtdInfo? dtdInfo = _coreReaderImpl.DtdInfo;
if (dtdInfo != null)
{
switch (_validationType)
}
// 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)
{
}
}
- internal override XmlNamespaceManager NamespaceManager
+ internal override XmlNamespaceManager? NamespaceManager
{
get
{
}
}
- internal object SchemaTypeObject
+ internal object? SchemaTypeObject
{
set
{
}
}
- internal object TypedValueObject
+ internal object? TypedValueObject
{
get
{
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);
}
}
// 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;
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}");
_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;
_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;
_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;
_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;
}
}
- public override string XmlLang
+ public override string? XmlLang
{
get
{
}
}
- public override async Task WriteCDataAsync(string text)
+ public override async Task WriteCDataAsync(string? text)
{
try
{
{
text = string.Empty;
}
+
await AdvanceStateAsync(Token.CData).ConfigureAwait(false);
await _writer.WriteCDataAsync(text).ConfigureAwait(false);
}
}
}
- public override async Task WriteCommentAsync(string text)
+ public override async Task WriteCommentAsync(string? text)
{
try
{
{
text = string.Empty;
}
+
await AdvanceStateAsync(Token.Comment).ConfigureAwait(false);
await _writer.WriteCommentAsync(text).ConfigureAwait(false);
}
}
}
- public override async Task WriteWhitespaceAsync(string ws)
+ public override async Task WriteWhitespaceAsync(string? ws)
{
try
{
{
ws = string.Empty;
}
+
if (!XmlCharType.Instance.IsOnlyWhitespace(ws))
{
throw new ArgumentException(SR.Xml_NonWhitespace);
}
}
- public override Task WriteStringAsync(string text)
+ public override Task WriteStringAsync(string? text)
{
try
{
await _nsStack[i].WriteDeclAsync(_writer, _rawWriter).ConfigureAwait(false);
}
}
+
if (_rawWriter != null)
{
_rawWriter.StartElementContent();
{
_rawWriter.StartElementContent();
}
+
return Task.CompletedTask;
}
// 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
{
{
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);
}
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)
{
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)
{
writer.WriteStartAttribute("xmlns", prefix, XmlReservedNs.NsXmlNs);
}
+
writer.WriteString(namespaceUri);
writer.WriteEndAttribute();
}
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;
}
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;
BufferChunk bufChunk;
for (int i = _firstItem; i <= _lastItem; i++)
{
- Item item = _items[i];
+ Item item = _items![i];
switch (item.type)
{
case ItemType.EntityRef:
int i = _firstItem;
while (i == _firstItem && i <= _lastItem)
{
- Item item = _items[i];
+ Item item = _items![i];
switch (item.type)
{
case ItemType.Whitespace:
bufChunk.index++;
bufChunk.count--;
}
+
if (bufChunk.index == endIndex)
{
// no characters left -> move the firstItem index to exclude it from the Replay
_firstItem++;
}
+
break;
}
i++;
i = _lastItem;
while (i == _lastItem && i >= _firstItem)
{
- Item item = _items[i];
+ Item item = _items![i];
switch (item.type)
{
case ItemType.Whitespace:
{
bufChunk.count--;
}
+
if (bufChunk.count == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
_lastItem--;
}
+
break;
}
+
i--;
}
}
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;
}
}
// 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;
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)
BufferChunk bufChunk;
for (int i = _firstItem; i <= _lastItem; i++)
{
- Item item = _items[i];
+ Item item = _items![i];
switch (item.type)
{
case ItemType.EntityRef:
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);
}
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);
}
// 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;
//
// 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()
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);
}
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);
}
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);
}
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);
}
writer.Flush();
}
- public override string LookupPrefix(string ns)
+ public override string? LookupPrefix(string ns)
{
return writer.LookupPrefix(ns);
}
writer.WriteValue(value);
}
- public override void WriteValue(string value)
+ public override void WriteValue(string? value)
{
writer.WriteValue(value);
}
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);
}
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);
}
// Writes out a <![CDATA[...]]>; 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();
}
// 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();
}
// 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;
private List<XmlQualifiedName> _cdataSections = new List<XmlQualifiedName>();
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;
{
return _encoding;
}
+ [MemberNotNull(nameof(_encoding))]
set
{
CheckReadOnly(nameof(Encoding));
{
throw new ArgumentOutOfRangeException(nameof(value));
}
+
_newLineHandling = value;
}
}
{
return _newLineChars;
}
+ [MemberNotNull(nameof(_newLineChars))]
set
{
CheckReadOnly(nameof(NewLineChars));
{
throw new ArgumentNullException(nameof(value));
}
+
_newLineChars = value;
}
}
{
return _indentChars;
}
+ [MemberNotNull(nameof(_indentChars))]
set
{
CheckReadOnly(nameof(IndentChars));
{
throw new ArgumentNullException(nameof(value));
}
+
_indentChars = value;
}
}
// 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<XmlQualifiedName>(_cdataSections);
}
// Used in Html writer when writing Meta element. Null denotes the default media type.
- internal string MediaType
+ internal string? MediaType
{
get
{
}
// System Id in doc-type declaration. Null denotes the absence of the system Id.
- internal string DocTypeSystem
+ internal string? DocTypeSystem
{
get
{
}
// Public Id in doc-type declaration. Null denotes the absence of the public Id.
- internal string DocTypePublic
+ internal string? DocTypePublic
{
get
{
newSettings.CloseOutput = true;
}
- FileStream fs = null;
+ FileStream? fs = null;
try
{
// open file stream
//
// Private methods
//
+ [MemberNotNull(nameof(_encoding))]
+ [MemberNotNull(nameof(_newLineChars))]
+ [MemberNotNull(nameof(_indentChars))]
private void Initialize()
{
_encoding = Encoding.UTF8;
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;
// 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;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
+using System.Diagnostics.CodeAnalysis;
namespace System.Xml
{
private ValidatingReaderNodeData[] _contentEvents;
private ValidatingReaderNodeData[] _attributeEvents;
- private ValidatingReaderNodeData _cachedNode;
+ private ValidatingReaderNodeData? _cachedNode;
private CachingReaderState _cacheState;
private int _contentIndex;
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;
Init();
}
+ [MemberNotNull(nameof(_coreReaderNameTable))]
private void Init()
{
_coreReaderNameTable = _coreReader.NameTable;
}
// Settings
- public override XmlReaderSettings Settings
+ public override XmlReaderSettings? Settings
{
get
{
{
get
{
- return _cachedNode.NodeType;
+ return _cachedNode!.NodeType;
}
}
{
get
{
- return _cachedNode.GetAtomizedNameWPrefix(_coreReaderNameTable);
+ return _cachedNode!.GetAtomizedNameWPrefix(_coreReaderNameTable);
}
}
{
get
{
- return _cachedNode.LocalName;
+ return _cachedNode!.LocalName;
}
}
{
get
{
- return _cachedNode.Namespace;
+ return _cachedNode!.Namespace;
}
}
{
get
{
- return _cachedNode.Prefix;
+ return _cachedNode!.Prefix;
}
}
{
get
{
- return XmlReader.HasValueInternal(_cachedNode.NodeType);
+ return XmlReader.HasValueInternal(_cachedNode!.NodeType);
}
}
{
get
{
- return _returnOriginalStringValues ? _cachedNode.OriginalStringValue : _cachedNode.RawValue;
+ return _returnOriginalStringValues ? _cachedNode!.OriginalStringValue! : _cachedNode!.RawValue;
}
}
{
get
{
- return _cachedNode.Depth;
+ return _cachedNode!.Depth;
}
}
// Gets the base URI of the current node.
- public override string BaseURI
+ public override string? BaseURI
{
get
{
}
// 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(':'))
{
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;
}
{
throw new ArgumentOutOfRangeException(nameof(i));
}
+
return _attributeEvents[i].RawValue;
}
}
// 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
{
}
// 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;
return true;
}
}
+
return false;
}
// 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();
goto case CachingReaderState.Record;
case CachingReaderState.Record:
- ValidatingReaderNodeData recordedNode = null;
+ ValidatingReaderNodeData? recordedNode = null;
if (_coreReader.Read())
{
switch (_coreReader.NodeType)
}
}
- 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);
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));
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)
}
// 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);
}
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;
}
{
get
{
- return _cachedNode.LineNumber;
+ return _cachedNode!.LineNumber;
}
}
{
get
{
- return _cachedNode.LinePosition;
+ return _cachedNode!.LinePosition;
}
}
return _coreReader;
}
- internal IXmlLineInfo GetLineInfo()
+ internal IXmlLineInfo? GetLineInfo()
{
return _lineInfo;
}
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;
}
private int GetAttributeIndexWithPrefix(string name)
{
- name = _coreReaderNameTable.Get(name);
- if (name == null)
+ string? atomizedName = _coreReaderNameTable.Get(name);
+ if (atomizedName == null)
{
return -1;
}
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;
}
{
_textNode = new ValidatingReaderNodeData(XmlNodeType.Text);
}
+
_textNode.Depth = depth;
_textNode.RawValue = attributeValue;
return _textNode;
{
if (_returnOriginalStringValues)
{
- return Task.FromResult(_cachedNode.OriginalStringValue);
+ return Task.FromResult(_cachedNode!.OriginalStringValue!);
}
else
{
- return Task.FromResult(_cachedNode.RawValue);
+ return Task.FromResult(_cachedNode!.RawValue);
}
}
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)
}
// 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);
// 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;
{
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;
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;
public bool Validate(XmlNode nodeToValidate)
{
- XmlSchemaObject partialValidationType = null;
+ XmlSchemaObject? partialValidationType = null;
XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
Debug.Assert(nodeToValidate.SchemaInfo != null);
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)
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);
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);
_attributeSchemaInfo = new XmlSchemaInfo();
}
ValidateNode(nodeToValidate);
- _validator.EndValidation();
+ _validator!.EndValidation();
return _isValid;
}
IDictionary<string, string> dictionary = _nsManager.GetNamespacesInScope(scope);
if (scope != XmlNamespaceScope.Local)
{
- XmlNode node = _startNode;
+ XmlNode? node = _startNode;
while (node != null)
{
switch (node.NodeType)
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;
}
{
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);
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:
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);
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:
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++)
{
_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);
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);
}
}
private void ValidateAttributes(XmlElement elementNode)
{
XmlAttributeCollection attributes = elementNode.Attributes;
- XmlAttribute attr = null;
+ XmlAttribute? attr = null;
for (int i = 0; i < attributes.Count; i++)
{
{ //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);
{
_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);
_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<string, string> namespaceDecls = NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.All);
- string defaultPrefix = null;
+ string? defaultPrefix = null;
string defaultNS;
attributeNS = _nameTable.Add(attributeNS); //atomize ns
}
}
}
+
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
//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;
}
}
- 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;
}
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);
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
_validator.ValidateEndOfAttributes(null);
if (i > 0)
{
- ValidateChildrenTillNextAncestor(node, _nodeSequenceToValidate[i - 1]);
+ ValidateChildrenTillNextAncestor(node, _nodeSequenceToValidate[i - 1]!);
}
else
{ //i == 0
}
}
- 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;
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;
{
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++)
{
_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)
{
{
break;
}
+
switch (child.NodeType)
{
case XmlNodeType.EntityReference:
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:
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);
{ //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)
{
}
}
- 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)
// 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;
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<XmlNode> _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)
{
_settings.ReadOnly = true;
}
- public XmlNamespaceManager NamespaceManager
+ public XmlNamespaceManager? NamespaceManager
{
set
{
}
}
- public DocumentXPathNavigator Navigator
+ public DocumentXPathNavigator? Navigator
{
set
{
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);
}
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);
{
throw new InvalidOperationException();
}
+
_write = _write.ParentNode;
}
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;
}
// 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);
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;
}
{
attr = _document.CreateAttribute(_document.strXmlns, prefix, _document.strReservedXmlns);
}
+
AddAttribute(attr, _write);
_write = attr;
}
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);
AddChild(node, _write);
}
- public override void WriteComment(string text)
+ public override void WriteComment(string? text)
{
VerifyState(Method.WriteComment);
XmlConvert.VerifyCharData(text, ExceptionType.ArgumentException);
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);
}
WriteString(char.ToString(ch));
}
- public override void WriteWhitespace(string text)
+ public override void WriteWhitespace(string? text)
{
VerifyState(Method.WriteWhitespace);
XmlConvert.VerifyCharData(text, ExceptionType.ArgumentException);
}
}
- public override void WriteString(string text)
+ public override void WriteString(string? text)
{
VerifyState(Method.WriteString);
XmlConvert.VerifyCharData(text, ExceptionType.ArgumentException);
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;
{
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();
{
throw new InvalidOperationException(SR.Xpn_NoContent);
}
+
CloseWithReplaceToFollowingSibling();
break;
}
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
}
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);
}
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))
{
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()
IDictionary<string, string> 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)
{
}
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)
{
{
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;
{
return State.Fragment;
}
+
break;
case DocumentXmlWriterType.PrependChild:
case DocumentXmlWriterType.AppendChild:
{
return State.Fragment;
}
+
break;
case DocumentXmlWriterType.AppendAttribute:
return State.Attribute;
// 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;
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)
{
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)
{
name = tmp;
}
}
+
_entries = newEntries;
_mask = newMask;
}
// 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;
internal class XPathNodeList : XmlNodeList
{
- private readonly List<XmlNode> _list;
+ private readonly List<XmlNode?> _list;
private readonly XPathNodeIterator _nodeIterator;
private bool _done;
public XPathNodeList(XPathNodeIterator nodeIterator)
{
_nodeIterator = nodeIterator;
- _list = new List<XmlNode>();
+ _list = new List<XmlNode?>();
_done = false;
}
return count;
}
- public override XmlNode Item(int index)
+ public override XmlNode? Item(int index)
{
if (_list.Count <= index)
{
{
return null;
}
+
return _list[index];
}
return _valid;
}
- public object Current
+ public object? Current
{
get
{
{
return _list[_index];
}
+
return null;
}
}
// 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
{
public class XmlAttribute : XmlNode
{
private XmlName _name;
- private XmlLinkedNode _lastChild;
+ private XmlLinkedNode? _lastChild;
internal XmlAttribute(XmlName name, XmlDocument doc) : base(doc)
{
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)
{
}
}
// Gets the parent of this node (for nodes that can have parents).
- public override XmlNode ParentNode
+ public override XmlNode? ParentNode
{
get { return null; }
}
}
// 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
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);
//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);
return newNode;
}
- internal override XmlLinkedNode LastNode
+ internal override XmlLinkedNode? LastNode
{
get { return _lastChild; }
set { _lastChild = value; }
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);
}
{
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);
}
{
node = base.InsertAfter(newChild, refChild);
}
+
return node;
}
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
- string innerText = InnerText;
+ string? innerText = InnerText;
node = base.ReplaceChild(newChild, oldChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
- string innerText = InnerText;
+ string? innerText = InnerText;
node = base.RemoveChild(oldChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
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);
}
{
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);
}
{
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
{
// 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);
}
}
}
- internal override void SetParent(XmlNode node)
+ internal override void SetParent(XmlNode? node)
{
this.parentNode = node;
}
// 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
{
// Gets the attribute with the specified name.
[System.Runtime.CompilerServices.IndexerName("ItemOf")]
- public XmlAttribute this[string name]
+ public XmlAttribute? this[string name]
{
get
{
// 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
{
return i;
}
}
+
return -1;
}
}
// 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;
}
// 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;
}
// 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;
}
// 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++)
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;
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
//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
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);
// 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;
// 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)
{
}
{
get
{
- return OwnerDocument.strCDataSectionName;
+ return OwnerDocument!.strCDataSectionName;
}
}
{
get
{
- return OwnerDocument.strCDataSectionName;
+ return OwnerDocument!.strCDataSectionName;
}
}
}
}
- public override XmlNode ParentNode
+ public override XmlNode? ParentNode
{
get
{
- switch (parentNode.NodeType)
+ switch (parentNode!.NodeType)
{
case XmlNodeType.Document:
return null;
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;
}
}
- public override XmlNode PreviousText
+ public override XmlNode? PreviousText
{
get
{
- if (parentNode.IsText)
+ if (parentNode != null && parentNode.IsText)
{
return parentNode;
}
+
return null;
}
}
// 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;
// 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; }
// 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
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);
{
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);
}
// 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);
}
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);
// 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)
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);
AfterEvent(args);
}
- internal bool CheckOnData(string data)
+ internal bool CheckOnData(string? data)
{
return XmlCharType.Instance.IsOnlyWhitespace(data);
}
//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;
xnt = XPathNodeType.Text;
return false;
case XmlNodeType.EntityReference:
- if (!DecideXPNodeTypeForTextNodes(node.FirstChild, ref xnt))
+ if (!DecideXPNodeTypeForTextNodes(n.FirstChild!, ref xnt))
{
return false;
}
default:
return false;
}
- node = node.NextSibling;
+ n = n.NextSibling;
}
return true;
}
// 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
internal sealed class XmlChildEnumerator : IEnumerator
{
internal XmlNode container;
- internal XmlNode child;
+ internal XmlNode? child;
internal bool isFirst;
internal XmlChildEnumerator(XmlNode container)
// 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
_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;
}
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;
}
}
// 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;
// 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.
// 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;
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);
public string Version
{
get { return _version; }
+ [MemberNotNull(nameof(_version))]
internal set { _version = value; }
}
// Specifies the value of the encoding attribute, as for
// <?xml version= '1.0' encoding= 'UTF-8' ?>
+ [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)
}
}
- public override string Value
+ public override string? Value
{
get { return InnerText; }
- set { InnerText = value; }
+ set { InnerText = value!; }
}
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);
{
if (tempVersion != null && !IsValidXmlVersion(tempVersion))
throw new ArgumentException(SR.Xdom_Version);
- Version = tempVersion;
+ Version = tempVersion!;
if (tempEncoding != null)
Encoding = tempEncoding;
// 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;
using System.Security;
using System.Globalization;
using System.Runtime.Versioning;
+using System.Diagnostics.CodeAnalysis;
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;
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);
}
}
- internal SchemaInfo DtdSchemaInfo
+ internal SchemaInfo? DtdSchemaInfo
{
get { return _schemaInfo; }
set { _schemaInfo = value; }
}
}
- 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));
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));
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;
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)
gcElemRefs.Add(elemRef);
else
{
- if ((XmlElement)(elemRef.Target) == elem)
+ if ((XmlElement?)(elemRef.Target) == elem)
return elemRef;
}
}
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));
}
{
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);
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;
}
// 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
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; }
}
get { return bSetResolver; }
}
- internal XmlResolver GetResolver()
+ internal XmlResolver? GetResolver()
{
return _resolver;
}
if (!bSetResolver)
bSetResolver = true;
- XmlDocumentType dtd = this.DocumentType;
+ XmlDocumentType? dtd = this.DocumentType;
if (dtd != null)
{
dtd.DtdSchemaInfo = null;
}
// 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)
// 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)
return false;
}
- internal override bool CanInsertBefore(XmlNode newChild, XmlNode refChild)
+ internal override bool CanInsertBefore(XmlNode newChild, XmlNode? refChild)
{
if (refChild == null)
refChild = FirstChild;
return false;
}
- internal override bool CanInsertAfter(XmlNode newChild, XmlNode refChild)
+ internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild)
{
if (refChild == null)
refChild = LastChild;
}
// 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);
}
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<XmlQualifiedName, SchemaAttDef> attrDefs in ed.AttDefs)
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;
}
}
}
- 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;
//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);
}
// 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)
}
while (parent != null);
}
- node = NormalizeText(node);
+ node = NormalizeText(node)!;
break;
case XmlNodeType.Whitespace:
parent = node.ParentNode;
}
while (parent != null);
}
- node = NormalizeText(node);
+ node = NormalizeText(node)!;
break;
default:
break;
}
}
- 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;
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);
}
// 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;
// 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;
}
// 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;
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:
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;
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));
}
// 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)
// 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)
{
// 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;
{
IsLoading = false;
}
+
return node;
}
}
//TextEncoding is the one from XmlDeclaration if there is any
- internal Encoding TextEncoding
+ internal Encoding? TextEncoding
{
get
{
}
}
+ [AllowNull]
public override string InnerText
{
set
//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);
}
}
- 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
}
}
- 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;
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);
}
// 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<XmlQualifiedName, SchemaAttDef> attrDefs in ed.AttDefs)
{
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
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;
}
{
if (_reportValidity)
{
- XmlElement documentElement = DocumentElement;
+ XmlElement? documentElement = DocumentElement;
if (documentElement != null)
{
switch (documentElement.SchemaInfo.Validity)
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);
// 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;
// such as <code>insertBefore()</code> and <code>appendChild()</code>.
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.
}
// Gets the parent of this node (for nodes that can have parents).
- public override XmlNode ParentNode
+ public override XmlNode? ParentNode
{
get { return null; }
}
{
get
{
- return (XmlDocument)parentNode;
+ return (XmlDocument)parentNode!;
}
}
get { return true; }
}
- internal override XmlLinkedNode LastNode
+ internal override XmlLinkedNode? LastNode
{
get { return _lastChild; }
set { _lastChild = value; }
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
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)
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)
// 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;
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;
//
// 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; }
}
// Intentionally do nothing
}
- internal SchemaInfo DtdSchemaInfo
+ internal SchemaInfo? DtdSchemaInfo
{
get
{
// 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;
// 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)
{
}
// 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);
}
// 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;
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)
{
}
if (name.LocalName.Length == 0)
throw new ArgumentException(SR.Xdom_Empty_LocalName);
+
_name = name;
if (empty)
{
}
}
- 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)
{
}
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);
element.Attributes.InternalAppendAttribute(newAttr);
}
}
+
if (deep)
element.CopyChildren(doc, this, deep);
get { return XmlNodeType.Element; }
}
- public override XmlNode ParentNode
+ public override XmlNode? ParentNode
{
get
{
//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);
}
}
- internal override XmlLinkedNode LastNode
+ internal override XmlLinkedNode? LastNode
{
get
{
return _lastChild == this ? null : _lastChild;
}
-
set
{
_lastChild = value;
// 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;
}
// 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);
}
// Returns the XmlAttribute with the specified name.
- public virtual XmlAttribute GetAttributeNode(string name)
+ public virtual XmlAttribute? GetAttributeNode(string name)
{
if (HasAttributes)
return Attributes[name];
{
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;
}
//
// 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);
}
// 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];
}
// 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;
}
// 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;
}
}
// 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;
// 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);
}
// 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;
}
{
if (HasAttributes)
{
- _attributes.RemoveAll();
+ _attributes!.RemoveAll();
}
}
}
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
}
}
- 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;
}
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;
}
}
// 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;
{
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
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)
{
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;
if (args.Action == XmlNodeChangedAction.Insert)
_empty = false;
}
+
_matchCount = -1;
}
_localName = localName;
_namespaceURI = namespaceURI;
}
+
_name = null;
}
}
// 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
}
// 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)
{
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)
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;
return GetMatchingNode(node, true);
}
- public override XmlNode Item(int index)
+ public override XmlNode? Item(int index)
{
if (_rootNode == null || index < 0)
return null;
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;
}
{
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;
}
}
public override IEnumerator GetEnumerator()
{
if (_empty == true)
- return new XmlEmptyElementListEnumerator(this); ;
+ return new XmlEmptyElementListEnumerator(this);
+
return new XmlElementListEnumerator(this);
}
{
if (_listener != null)
{
- XmlElementListListener listener = (XmlElementListListener)_listener.Target;
+ XmlElementListListener? listener = (XmlElementListListener?)_listener.Target;
if (listener != null)
{
listener.Unregister();
}
+
_listener = null;
}
}
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)
_changeCount = _list.ChangeCount;
}
- public object Current
+ public object? Current
{
get { return _curElem; }
}
{
}
- public object Current
+ public object? Current
{
get { return null; }
}
internal class XmlElementListListener
{
- private WeakReference _elemList;
+ private WeakReference? _elemList;
private readonly XmlDocument _doc;
private readonly XmlNodeChangedEventHandler _nodeChangeHandler;
{
if (_elemList != null)
{
- XmlElementList el = (XmlElementList)_elemList.Target;
+ XmlElementList? el = (XmlElementList?)_elemList.Target;
if (null != el)
{
el.ConcurrencyCheck(args);
// 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;
get { return true; }
}
- internal override XmlLinkedNode LastNode
+ internal override XmlLinkedNode? LastNode
{
get
{
}
// 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; }
}
// 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
public class XmlEntityReference : XmlLinkedNode
{
private readonly string _name;
- private XmlLinkedNode _lastChild;
+ private XmlLinkedNode? _lastChild;
protected internal XmlEntityReference(string name, XmlDocument doc) : base(doc)
{
throw new ArgumentException(SR.Xdom_InvalidCharacter_EntityReference);
}
}
+
_name = doc.NameTable.Add(name);
doc.fEntRefNodesPresent = true;
}
}
// Gets or sets the value of the node.
- public override string Value
+ public override string? Value
{
get
{
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)
this.SetParent(node);
}
- internal override XmlLinkedNode LastNode
+ internal override XmlLinkedNode? LastNode
{
get
{
{
get
{
- return OwnerDocument.BaseURI;
+ return OwnerDocument!.BaseURI;
}
}
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))
else
return ent.BaseURI;
}
+
return string.Empty;
}
}
// 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
// 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
// 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)
{
}
// 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;
}
}
// 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;
{
internal class XmlLoader
{
- private XmlDocument _doc;
- private XmlReader _reader;
+ private XmlDocument? _doc;
+ private XmlReader? _reader;
private bool _preserveWhitespace;
-
public XmlLoader()
{
}
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)
{
{
Debug.Assert(_reader != null);
Debug.Assert(parentDoc != null);
- XmlNode node = null;
+ XmlNode? node = null;
while ((node = LoadNode(true)) != null)
{
parentDoc.AppendChildForLoad(node, parentDoc);
}
}
- internal XmlNode ReadCurrentNode(XmlDocument doc, XmlReader reader)
+ internal XmlNode? ReadCurrentNode(XmlDocument doc, XmlReader reader)
{
_doc = doc;
_reader = reader;
}
if (reader.ReadState == ReadState.Interactive)
{
- XmlNode n = LoadNode(true);
+ XmlNode n = LoadNode(true)!;
// Move to the next node
if (n.NodeType != XmlNodeType.Attribute)
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())
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)
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)
continue;
}
case XmlNodeType.CDATA:
- node = _doc.CreateCDataSection(r.Value);
+ node = _doc!.CreateCDataSection(r.Value);
break;
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:
Debug.Assert(node != null);
if (parent != null)
{
- parent.AppendChildForLoad(node, _doc);
+ parent.AppendChildForLoad(node, _doc!);
}
else
{
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)
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;
default:
throw UnexpectedNodeType(r.NodeType);
}
+
Debug.Assert(node != null);
attr.AppendChildForLoad(node, _doc);
}
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);
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);
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();
// 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;
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
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())
}
}
- 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
// 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())
// recursively load all children.
if (!fEmptyElement)
{
- parent.AppendChildForLoad(element, _doc);
+ parent!.AppendChildForLoad(element, _doc!);
parent = element;
continue;
}
}
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;
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
{
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
{
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;
}
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());
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)
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);
if (schInfo != null)
{
//set the schema information into the document
- _doc.DtdSchemaInfo = schInfo;
+ _doc!.DtdSchemaInfo = schInfo;
// Notation hashtable
if (schInfo.Notations != null)
}
#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<string> prefixes = new HashSet<string>();
// 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();
}
}
}
+
node = node.ParentNode;
}
return new XmlParserContext(
if (nt == XmlNodeType.Entity)
{
- XmlNode node = null;
+ XmlNode? node = null;
while (_reader.Read() && (node = LoadNodeDirect()) != null)
{
parentNode.AppendChildForLoad(node, _doc);
}
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)
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)
}
}
//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();
}
{
//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)
{
}
Debug.Assert(tr.EntityHandling == EntityHandling.ExpandCharEntities);
- XmlDocumentType dtdNode = doc.DocumentType;
+ XmlDocumentType? dtdNode = doc.DocumentType;
if (dtdNode != null)
{
tr.Namespaces = dtdNode.ParseWithNamespaces;
}
#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();
// 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;
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)
{
}
}
- public virtual XmlSchemaSimpleType MemberType
+ public virtual XmlSchemaSimpleType? MemberType
{
get
{
}
}
- public virtual XmlSchemaType SchemaType
+ public virtual XmlSchemaType? SchemaType
{
get
{
}
}
- public virtual XmlSchemaElement SchemaElement
+ public virtual XmlSchemaElement? SchemaElement
{
get
{
}
}
- public virtual XmlSchemaAttribute SchemaAttribute
+ public virtual XmlSchemaAttribute? SchemaAttribute
{
get
{
}
}
- public virtual bool Equals(IXmlSchemaInfo schemaInfo)
+ public virtual bool Equals(IXmlSchemaInfo? schemaInfo)
{
return schemaInfo == null;
}
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
_schemaType = schemaInfo.SchemaType;
_decl = schemaInfo.SchemaElement != null
? (object)schemaInfo.SchemaElement
- : (object)schemaInfo.SchemaAttribute;
+ : (object?)schemaInfo.SchemaAttribute;
}
public override XmlSchemaValidity Validity
}
}
- public override XmlSchemaSimpleType MemberType
+ public override XmlSchemaSimpleType? MemberType
{
get
{
}
}
- public override XmlSchemaType SchemaType
+ public override XmlSchemaType? SchemaType
{
get
{
}
}
- public override XmlSchemaElement SchemaElement
+ public override XmlSchemaElement? SchemaElement
{
get
{
}
}
- public override XmlSchemaAttribute SchemaAttribute
+ public override XmlSchemaAttribute? SchemaAttribute
{
get
{
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;
}
// 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
{
// object.
// Otherwise, field is an List<object>. Once the field upgrades to an List<object>, it
// never degrades back, even if all elements are removed.
- private object _field;
+ private object? _field;
public int Count
{
if (_field == null)
return 0;
- List<object> list = _field as List<object>;
+ List<object>? list = _field as List<object>;
if (list != null)
return list.Count;
if (_field == null)
throw new ArgumentOutOfRangeException(nameof(index));
- List<object> list = _field as List<object>;
+ List<object>? list = _field as List<object>;
if (list != null)
return list[index];
{
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<object> temp = new List<object>();
- temp.Add(null);
+ temp.Add(null!);
_field = temp;
}
else
return;
}
- List<object> list = _field as List<object>;
+ List<object>? list = _field as List<object>;
if (list != null)
{
list.Add(value);
if (_field == null)
throw new ArgumentOutOfRangeException(nameof(index));
- List<object> list = _field as List<object>;
+ List<object?>? list = _field as List<object?>;
if (list != null)
{
list.RemoveAt(index);
return;
}
- List<object> list = _field as List<object>;
+ List<object>? list = _field as List<object>;
if (list != null)
{
list.Insert(index, value);
{
throw new InvalidOperationException();
}
+
return _loneValue;
}
}
_position = 0;
return true;
}
+
_position = 1;
return false;
}
return XmlDocument.EmptyEnumerator;
}
- List<object> list = _field as List<object>;
+ List<object>? list = _field as List<object>;
if (list != null)
{
return list.GetEnumerator();
// 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
}
// 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;
}
// 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;
}
}
// 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;
//
// 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;
}
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++)
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);
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;
}
{
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);
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);
// 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;
using System.Xml.XPath;
using MS.Internal.Xml.XPath;
using System.Globalization;
+using System.Diagnostics.CodeAnalysis;
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()
{
{
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));
}
// 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())); }
}
// Gets the parent of this node (for nodes that can have parents).
- public virtual XmlNode ParentNode
+ public virtual XmlNode? ParentNode
{
get
{
}
// 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;
}
}
}
// 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
{
}
// 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;
}
// Gets the last child of this node.
- public virtual XmlNode LastChild
+ public virtual XmlNode? LastChild
{
get { return LastNode; }
}
get { return false; }
}
- internal virtual XmlLinkedNode LastNode
+ internal virtual XmlLinkedNode? LastNode
{
get { return null; }
set { }
internal bool AncestorNode(XmlNode node)
{
- XmlNode n = this.ParentNode;
+ XmlNode? n = this.ParentNode;
while (n != null && n != this)
{
//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);
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);
// 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);
// insert the rest of the children after this one.
InsertAfter(newChild, node);
}
+
return first;
}
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);
if (refNode == FirstChild)
{
newNode.next = refNode;
- LastNode.next = newNode;
+ LastNode!.next = newNode;
newNode.SetParent(this);
if (newNode.IsText)
}
else
{
- XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling;
+ XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling!;
newNode.next = refNode;
prevNode.next = newNode;
}
// 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);
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);
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;
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);
}
else
{
- XmlLinkedNode nextNode = refNode.next;
+ XmlLinkedNode nextNode = refNode.next!;
newNode.next = nextNode;
refNode.next = newNode;
// 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;
}
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)
{
}
else
{
- XmlLinkedNode nextNode = oldNode.next;
+ XmlLinkedNode nextNode = oldNode.next!;
if (nextNode.IsText)
{
}
}
- lastNode.next = nextNode;
+ lastNode!.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
{
if (oldNode == lastNode)
{
- XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
+ XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling!;
prevNode.next = oldNode.next;
LastNode = prevNode;
oldNode.next = null;
}
else
{
- XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
- XmlLinkedNode nextNode = oldNode.next;
+ XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling!;
+ XmlLinkedNode nextNode = oldNode.next!;
if (nextNode.IsText)
{
}
// 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;
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;
}
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)
//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)
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;
}
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);
}
// 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:
case XmlNodeType.SignificantWhitespace:
{
sb.Append(crtChild.Value);
- XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild);
+ XmlNode? winner = NormalizeWinner(firstChildTextLikeNode, crtChild);
if (winner == firstChildTextLikeNode)
{
this.RemoveChild(crtChild);
this.RemoveChild(firstChildTextLikeNode);
firstChildTextLikeNode = crtChild;
}
+
break;
}
case XmlNodeType.Element:
firstChildTextLikeNode.Value = sb.ToString();
firstChildTextLikeNode = null;
}
+
sb.Remove(0, sb.Length);
break;
}
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)
{
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)
{
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)
{
{
get
{
- XmlNode fc = FirstChild;
+ XmlNode? fc = FirstChild;
if (fc == null)
{
return string.Empty;
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);
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
else
{
RemoveAll();
- AppendChild(OwnerDocument.CreateTextNode(value));
+ AppendChild(OwnerDocument!.CreateTextNode(value));
}
}
}
{
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;
// of the current node.
public virtual void RemoveAll()
{
- XmlNode child = FirstChild;
- XmlNode sibling = null;
+ XmlNode? child = FirstChild;
+ XmlNode? sibling = null;
while (child != null)
{
{
if (NodeType == XmlNodeType.Document)
return (XmlDocument)this;
- return OwnerDocument;
+ return OwnerDocument!;
}
}
// 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)
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
- if (prefix.Length == 0)
+ if (pref.Length == 0)
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
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;
}
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;
}
// 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)
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)
{
}
}
- 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)
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;
break;
}
}
+
node = node.ParentNode;
- }
- while (node != null);
+ } while (node != null);
+
return XmlSpace.None;
}
}
{
get
{
- XmlNode node = this;
- XmlElement elem = null;
+ XmlNode? node = this;
+ XmlElement? elem = null;
do
{
elem = node as XmlElement;
if (elem.HasAttribute("xml:lang"))
return elem.GetAttribute("xml:lang");
}
+
node = node.ParentNode;
} while (node != null);
+
return string.Empty;
}
}
}
}
- internal virtual string GetXPAttribute(string localName, string namespaceURI)
+ internal virtual string? GetXPAttribute(string localName, string namespaceURI)
{
return string.Empty;
}
}
}
- public virtual XmlNode PreviousText
+ public virtual XmlNode? PreviousText
{
get
{
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:
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;
// 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;
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; } }
}
}
// 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);
// 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
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; }
// 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()
{
// 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;
internal class XmlNodeReaderNavigator
{
private XmlNode _curNode;
- private XmlNode _elemNode;
+ private XmlNode? _elemNode;
private XmlNode _logNode;
private int _attrIndex;
private int _logAttrIndex;
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;
if (nt == XmlNodeType.Document)
_doc = (XmlDocument)_curNode;
else
- _doc = node.OwnerDocument;
+ _doc = node.OwnerDocument!;
+
_nameTable = _doc.NameTable;
_nAttrInd = -1;
//initialize the caching variables
{
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))
//See comments in HasValue
get
{
- string retValue = null;
+ string? retValue = null;
XmlNodeType nt = _curNode.NodeType;
if (_nAttrInd != -1)
{
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
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)
private void InitDecAttr()
{
int i = 0;
- string strTemp = _doc.Version;
+ string? strTemp = _doc.Version;
if (strTemp != null && strTemp.Length != 0)
{
decNodeAttributes[i].name = strVersion;
_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)
return null;
}
- public string GetDeclarationAttr(int i)
+ public string? GetDeclarationAttr(int i)
{
if (_nDeclarationAttrCount == -1)
InitDecAttr();
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)
{
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)
return null;
}
- public string GetDocumentTypeAttr(int i)
+ public string? GetDocumentTypeAttr(int i)
{
if (_nDocTypeAttrCount == -1)
InitDocTypeAttr();
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;
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;
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);
}
else
{
- while (_curNode.NodeType != XmlNodeType.Attribute && ((_curNode = _curNode.ParentNode) != null))
+ while (_curNode.NodeType != XmlNodeType.Attribute && ((_curNode = _curNode.ParentNode!) != null))
level--;
}
+
_bOnAttrVal = false;
}
}
ResetToAttribute(ref level);
if (_curNode.NodeType == XmlNodeType.Attribute)
{
- _curNode = ((XmlAttribute)_curNode).OwnerElement;
+ _curNode = ((XmlAttribute)_curNode).OwnerElement!;
_attrIndex = -1;
level--;
nt = XmlNodeType.Element;
}
private bool MoveToAttributeFromElement(XmlElement elem, string name, string ns)
{
- XmlAttribute attr = null;
+ XmlAttribute? attr = null;
if (ns.Length == 0)
attr = elem.GetAttributeNode(name);
else
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)
{
if (_bCreatedOnAttribute)
return;
- XmlAttribute attr = null;
+ XmlAttribute? attr = null;
switch (_curNode.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Attribute:
CheckIndexCondition(attributeIndex);
- attr = ((XmlElement)_elemNode).Attributes[attributeIndex];
+ attr = ((XmlElement)_elemNode!).Attributes[attributeIndex];
if (attr != null)
{
_curNode = (XmlNode)attr;
XmlNodeType nt = _curNode.NodeType;
if (nt == XmlNodeType.Attribute)
{
- if (_attrIndex >= (_elemNode.Attributes.Count - 1))
+ if (_attrIndex >= (_elemNode!.Attributes!.Count - 1))
return false;
else
{
}
else if (nt == XmlNodeType.Element)
{
- if (_curNode.Attributes.Count > 0)
+ if (_curNode.Attributes!.Count > 0)
{
level++;
_elemNode = _curNode;
public bool MoveToParent()
{
- XmlNode parent = _curNode.ParentNode;
+ XmlNode? parent = _curNode.ParentNode;
if (parent != null)
{
_curNode = parent;
public bool MoveToFirstChild()
{
- XmlNode firstChild = _curNode.FirstChild;
+ XmlNode? firstChild = _curNode.FirstChild;
if (firstChild != null)
{
_curNode = firstChild;
_attrIndex = -1;
return true;
}
+
return false;
}
private bool MoveToNextSibling(XmlNode node)
{
- XmlNode nextSibling = node.NextSibling;
+ XmlNode? nextSibling = node.NextSibling;
if (nextSibling != null)
{
_curNode = nextSibling;
_attrIndex = -1;
return true;
}
+
return false;
}
if (_curNode.NodeType != XmlNodeType.Attribute)
return MoveToNextSibling(_curNode);
else
- return MoveToNextSibling(_elemNode);
+ return MoveToNextSibling(_elemNode!);
}
public bool MoveToElement()
return false;
}
- public string LookupNamespace(string prefix)
+ public string? LookupNamespace(string prefix)
{
if (_bCreatedOnAttribute)
return null;
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)
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
- XmlAttribute attr = elem.GetAttributeNode(attrName);
+ XmlAttribute? attr = elem.GetAttributeNode(attrName);
if (attr != null)
{
return attr.Value;
return null;
}
- internal string DefaultLookupNamespace(string prefix)
+ internal string? DefaultLookupNamespace(string prefix)
{
if (!_bCreatedOnAttribute)
{
return null;
}
- internal string LookupPrefix(string namespaceName)
+ internal string? LookupPrefix(string namespaceName)
{
if (_bCreatedOnAttribute || namespaceName == null)
{
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)
node = ((XmlAttribute)node).OwnerElement;
continue;
}
+
node = node.ParentNode;
}
+
return null;
}
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)
{
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")
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!));
}
}
}
node = ((XmlAttribute)node).OwnerElement;
continue;
}
+
node = node.ParentNode;
};
}
if (_curNode.NodeType == XmlNodeType.Attribute)
{
- XmlNode firstChild = _curNode.FirstChild;
+ XmlNode? firstChild = _curNode.FirstChild;
if (firstChild != null)
{
_curNode = firstChild;
}
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;
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)
{
private bool _bStartFromDocument;
private bool _bInReadBinary;
- private ReadContentAsBinaryHelper _readBinaryHelper;
+ private ReadContentAsBinaryHelper? _readBinaryHelper;
// Creates an instance of the XmlNodeReader class using the specified XmlNode.
{
throw new ArgumentNullException(nameof(node));
}
+
_readerNav = new XmlNodeReaderNavigator(node);
_curDepth = 0;
}
}
- public override IXmlSchemaInfo SchemaInfo
+ public override IXmlSchemaInfo? SchemaInfo
{
get
{
}
// 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())
}
// 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())
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.
}
// 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;
}
// 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;
_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;
_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;
_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;
_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;
private void FinishReadBinary()
{
_bInReadBinary = false;
- _readBinaryHelper.Finish();
+ _readBinaryHelper!.Finish();
}
//
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
{
// 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;
// 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;
}
// 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; }
}
// 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
}
// 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; }
}
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;
// 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;
// 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);
{
get
{
- return OwnerDocument.strSignificantWhitespaceName;
+ return OwnerDocument!.strSignificantWhitespaceName;
}
}
{
get
{
- return OwnerDocument.strSignificantWhitespaceName;
+ return OwnerDocument!.strSignificantWhitespaceName;
}
}
}
}
- public override XmlNode ParentNode
+ public override XmlNode? ParentNode
{
get
{
- switch (parentNode.NodeType)
+ switch (parentNode!.NodeType)
{
case XmlNodeType.Document:
return base.ParentNode;
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 OwnerDocument.CreateSignificantWhitespace(Data);
}
- public override string Value
+ public override string? Value
{
get
{
}
}
- public override XmlNode PreviousText
+ public override XmlNode? PreviousText
{
get
{
- if (parentNode.IsText)
+ if (parentNode != null && parentNode.IsText)
{
return parentNode;
}
+
return null;
}
}
// 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
// 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)
{
}
{
get
{
- return OwnerDocument.strTextName;
+ return OwnerDocument!.strTextName;
}
}
{
get
{
- return OwnerDocument.strTextName;
+ return OwnerDocument!.strTextName;
}
}
}
}
- public override XmlNode ParentNode
+ public override XmlNode? ParentNode
{
get
{
- switch (parentNode.NodeType)
+ switch (parentNode!.NodeType)
{
case XmlNodeType.Document:
return null;
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;
return OwnerDocument.CreateTextNode(Data);
}
- public override string Value
+ public override string? Value
{
get
{
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);
// 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));
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;
}
}
}
- public override XmlNode PreviousText
+ public override XmlNode? PreviousText
{
get
{
- if (parentNode.IsText)
+ if (parentNode != null && parentNode.IsText)
{
return parentNode;
}
+
return null;
}
}
// 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
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)
{
}
}
}
- 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;
}
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;
}
// 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
// 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);
{
get
{
- return OwnerDocument.strNonSignificantWhitespaceName;
+ return OwnerDocument!.strNonSignificantWhitespaceName;
}
}
{
get
{
- return OwnerDocument.strNonSignificantWhitespaceName;
+ return OwnerDocument!.strNonSignificantWhitespaceName;
}
}
}
}
- public override XmlNode ParentNode
+ public override XmlNode? ParentNode
{
get
{
- switch (parentNode.NodeType)
+ switch (parentNode!.NodeType)
{
case XmlNodeType.Document:
return base.ParentNode;
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:
}
}
- public override string Value
+ public override string? Value
{
get
{
return Data;
}
-
set
{
if (CheckOnData(value))
}
}
- public override XmlNode PreviousText
+ public override XmlNode? PreviousText
{
get
{
- if (parentNode.IsText)
+ if (parentNode != null && parentNode.IsText)
{
return parentNode;
}
+
return null;
}
}
// 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;
}
// 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
internal override Stream AsStream()
{
Assembly asm = GetType().Assembly;
- return asm.GetManifestResourceStream(_resourceName);
+ return asm.GetManifestResourceStream(_resourceName)!;
}
}
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);
}
}
//
// Fields
//
- private readonly XmlResolver _fallbackResolver;
+ private readonly XmlResolver? _fallbackResolver;
private readonly Dictionary<Uri, PreloadedData> _mappings;
private readonly XmlKnownDtds _preloadedDtds;
{
}
- 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<Uri> uriComparer)
+ public XmlPreloadedResolver(XmlResolver? fallbackResolver, XmlKnownDtds preloadedDtds, IEqualityComparer<Uri>? uriComparer)
{
_fallbackResolver = fallbackResolver;
_mappings = new Dictionary<Uri, PreloadedData>(16, uriComparer);
}
}
- 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 ->
}
}
}
+
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));
}
}
}
- 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)
{
throw new ArgumentNullException(nameof(value));
}
+
Add(uri, new ByteArrayChunk(value, 0, value.Length));
}
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;
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;
set { _baseUri = value; }
}
- public ValidationEventHandler EventHandler
+ public ValidationEventHandler? EventHandler
{
- get { return (ValidationEventHandler)_eventHandling.EventHandler; }
+ get { return (ValidationEventHandler?)_eventHandling!.EventHandler; }
}
public SchemaInfo? SchemaInfo
_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);
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);
SchemaAttDef attdef,
SchemaInfo sinfo,
IValidationEventHandling eventHandling,
- string baseUriStr
+ string? baseUriStr
)
{
try
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
XmlAttribute attr;
if (prefix.Length == 0)
{
- attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns, XmlReservedNs.NsXmlNs);
+ attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns!, XmlReservedNs.NsXmlNs);
}
else
{
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();
}
[MemberNotNull(nameof(_attPresence))]
private void Init()
{
- _nsManager = reader.NamespaceManager;
+ _nsManager = reader.NamespaceManager!;
if (_nsManager == null)
{
_nsManager = new XmlNamespaceManager(NameTable);
remove { _validationEventHandler -= value; }
}
- internal XmlResolver XmlResolver
+ internal XmlResolver? XmlResolver
{
set
{
get { return _sourceNodeObject; }
}
- protected internal void SetSourceObject(object sourceObject)
+ protected internal void SetSourceObject(object? sourceObject)
{
_sourceNodeObject = sourceObject;
}
namespace System.Xml.Schema
{
- public delegate object XmlValueGetter();
+ public delegate object? XmlValueGetter();
[Flags]
public enum XmlSchemaValidationFlags
object attValue;
if (attributeValueGetter != null)
{
- attValue = attributeValueGetter();
+ attValue = attributeValueGetter()!;
}
else
{
case XmlSchemaContentType.TextOnly:
if (elementValueGetter != null)
{
- SaveTextValue(elementValueGetter());
+ SaveTextValue(elementValueGetter()!);
}
else
{
break;
case XmlSchemaContentType.ElementOnly:
- string textValue = elementValueGetter != null ? elementValueGetter().ToString()! : elementStringValue!;
+ string textValue = elementValueGetter != null ? elementValueGetter()!.ToString()! : elementStringValue!;
if (_xmlCharType.IsOnlyWhitespace(textValue))
{
break;
{
if (elementValueGetter != null)
{
- SaveTextValue(elementValueGetter());
+ SaveTextValue(elementValueGetter()!);
}
else
{
case XmlSchemaContentType.TextOnly:
if (elementValueGetter != null)
{
- SaveTextValue(elementValueGetter());
+ SaveTextValue(elementValueGetter()!);
}
else
{
{
if (elementValueGetter != null)
{
- SaveTextValue(elementValueGetter());
+ SaveTextValue(elementValueGetter()!);
}
else
{
[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();
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)
{
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)
{