Sardothien
Sardothien

Reputation: 87

Validate xml with dtd

I just want to see if xml is valid with dtd and to print error message if it is not. I wrote this validator. The problem it that it prints always that document is valid, even it is not valid. Thanks for help.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema; 


namespace XMLValidator
{
    class Program
    {
        static void Main()
        {


            var messages = new StringBuilder();
            var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD };
            settings.ValidationEventHandler += (sender, args) => messages.AppendLine(args.Message);
            var reader = XmlReader.Create("file.xml", settings);


            if (messages.Length > 0)
            {
                Console.WriteLine("Document is not valid!");
            }
            else
                Console.WriteLine("Document is valid!");
        }

    }
}

Upvotes: 2

Views: 3726

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

You also need to enable DTD processing

var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD, DtdProcessing = DtdProcessing.Parse };

and of course you need to parse through the file using e.g.

while (reader.Read()) {}

Also if the DTD is in an external file then also set

var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD, DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() };

Upvotes: 6

Related Questions