如何使用XSD验证Xml

时间:2012-12-21 11:17:49

标签: c# xml xsd

此代码未正确验证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);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您似乎忘记了ValidationFlags

readSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
readSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
readSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

答案 1 :(得分:0)

这是一个使用linq到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);
    });
}