Validate xml with dtd

冷暖自知 提交于 2019-12-11 13:18:16

问题


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

    }
}

回答1:


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() };


来源:https://stackoverflow.com/questions/37361866/validate-xml-with-dtd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!