Microsoft Docs

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

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

See Also