Load XML while prohibiting DTD processing
Disabling external resolution and disabling validation are different settings. If the input contract does not permit document type declarations, reject DTDs explicitly at the reader boundary.
Load the DOM through that configured reader instead of passing arbitrary text directly to XmlDocument.LoadXml.
Configure the reader
In a .NET console project's Program.cs, run:
using System.Xml;
const string xml = "<settings><mode>preview</mode></settings>";
var settings = new XmlReaderSettings {
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
ValidationType = ValidationType.None,
MaxCharactersInDocument = 100_000
};
using var input = new StringReader(xml);
using var reader = XmlReader.Create(input, settings);
var document = new XmlDocument { XmlResolver = null };
document.Load(reader);
Console.WriteLine(document.SelectSingleNode("/settings/mode")?.InnerText);
dotnet run prints preview. Add <!DOCTYPE settings []> before the root element and the parser rejects the input with XmlException.
Set a policy, not just a property
ValidationType.None skips schema validation. It does not by itself express whether DTDs may be parsed. XmlResolver = null prevents external resource resolution. DtdProcessing.Prohibit rejects the declaration entirely.
Choose the size limit for the actual document contract and handle parse failures at the input boundary. A DOM stores the whole document, so use a streaming reader when documents are too large to hold in memory. Do not switch to DtdProcessing.Parse merely to make unexpected input succeed. That changes the accepted format.
Official references


Author: Herman Schoenfeld