1

此代码未正确验证 Xml 您能否找到错误.... 即使我使用 Invalid xml 执行它也不会引发任何错误

using System.Xml;

namespace XmlTryProject
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            XmlReaderSettings readSettings = new XmlReaderSettings();
            readSettings.ValidationType = ValidationType.Schema;
            readSettings.Schemas.Add(null,
     @"C:\Visual Studio 2010\Projects\XmlTry \XmlTryProject\EmployeeXSD.xsd");

            readSettings.ValidationEventHandler +=
                new System.Xml.Schema.ValidationEventHandler(Validater);

            XmlReader xReader = XmlReader.Create(
     @"C:\Visual Studio 2010\Projects\XmlTry\XmlTryProject\EmployeeXML.xml",
                readSettings);

            while (xReader.Read())
            {
                if (xReader.NodeType == XmlNodeType.Element)
                {
                    Console.WriteLine(xReader.Name);
                }
            }
        }

        public static void Validater(object sender,
                             System.Xml.Schema.ValidationEventArgs args)
        {
            Console.WriteLine(args.Message);
        }
    }
}
4

2 回答 2

3

看起来您忘记了ValidationFlags

readSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
readSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
readSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
于 2012-12-21T11:21:59.277 回答
0

这是一个使用 linq to xml 的简单方法。
ValidateXmlFile 方法是如何使用它的示例。

private static void ValidateXmlFile()
{
    using (var xmlFile = File.OpenRead("networkshares.xml"))
    using (var xmlSchemaFile = File.OpenRead("networkshares.xsd"))
    {
        ValidateXml("netuseperdomain.networkshares", xmlSchemaFile, xmlFile);
    }
}

public static void ValidateXml(string targetNamespace, Stream xmlSchema, Stream xml)
{
    var xdoc = XDocument.Load(xml);
    var schemas = new XmlSchemaSet();
    schemas.Add(targetNamespace, new XmlTextReader(xmlSchema));

    xdoc.Validate(schemas, (sender, e) =>
    {
        throw new Exception(e.Message);
    });
}
于 2012-12-21T11:24:29.663 回答