问题
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