使用 dtd 验证 xml

Validate xml with dtd

我只想看看 xml 是否对 dtd 有效,如果无效则打印错误消息。我写了这个验证器。问题是它始终打印该文档是有效的,即使它是无效的。感谢您的帮助。

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!");
        }

    }
}

您还需要启用 DTD 处理

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

当然你需要使用例如

解析文件
while (reader.Read()) {}

此外,如果 DTD 在外部文件中,则还设置

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