XmlDtdValidation Class
Namespace: System.Xml
Assembly: System.Xml.dll
Summary
The XmlDtdValidation class provides methods to validate XML documents against their Document Type Definition (DTD). It can be used with XmlReader or XmlDocument to enforce structural rules defined in a DTD.
Syntax
public sealed class XmlDtdValidation
{
public XmlDtdValidation();
public void Validate(XmlReader reader, ValidationEventHandler? validationEventHandler);
public bool IsValid { get; }
public IList<ValidationEventArgs> Errors { get; }
}
Members
Validate(XmlReader, ValidationEventHandler?)– Validates the XML content read by the suppliedXmlReader. Optionally receives a callback for validation events.IsValid– Gets a value indicating whether the last validation succeeded.Errors– Collection of validation errors encountered during the last validation operation.
Example
Remarks
See Also
Example: Validating an XML file against its DTD
using System;
using System.Xml;
using System.Xml.Schema;
class Program
{
static void Main()
{
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Parse,
ValidationType = ValidationType.DTD
};
settings.ValidationEventHandler += (sender, e) =>
{
Console.WriteLine($"Error: {e.Message}");
};
using (XmlReader reader = XmlReader.Create("sample.xml", settings))
{
XmlDtdValidation validator = new XmlDtdValidation();
validator.Validate(reader, null);
if (validator.IsValid)
Console.WriteLine("Document is valid.");
else
Console.WriteLine("Document is invalid. See errors above.");
}
}
}
This example demonstrates creating an XmlReader with DTD processing enabled, then using XmlDtdValidation to validate sample.xml. Validation errors are printed to the console.
Remarks
- The class is sealed and cannot be inherited.
- When
DtdProcessingis set toProhibit(the default), validation will not occur. You must enable DTD processing explicitly. - The
Validatemethod can be called multiple times with different readers;IsValidandErrorsreflect the most recent validation. - Performance considerations: Validation incurs additional processing overhead. For large documents, consider streaming validation.