11

我有在运行时读取的 xml 文件,是否可以在运行时针对 xsd 文件验证 xml?使用 c#

4

3 回答 3

15

试试这个:

public void ValidateXmlDocument(
    XmlReader documentToValidate, string schemaPath)
{
    XmlSchema schema;
    using (var schemaReader = XmlReader.Create(schemaPath))
    {
        schema = XmlSchema.Read(schemaReader, ValidationEventHandler);
    }

    var schemas = new XmlSchemaSet();
    schemas.Add(schema);

    var settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas = schemas;
    settings.ValidationFlags =
        XmlSchemaValidationFlags.ProcessIdentityConstraints |
        XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationEventHandler += ValidationEventHandler;

    using (var validationReader = XmlReader.Create(documentToValidate, settings))
    {
        while (validationReader.Read())
        {
        }
    }
}

private static void ValidationEventHandler(
    object sender, ValidationEventArgs args)
{
    if (args.Severity == XmlSeverityType.Error)
    {
        throw args.Exception;
    }

    Debug.WriteLine(args.Message);
}
于 2009-08-14T12:57:04.760 回答
5

我也有代码!我在测试中使用它:

    public static bool IsValid(XElement element, params string[] schemas)
    {
        XmlSchemaSet xsd = new XmlSchemaSet();
        XmlReader xr = null;
        foreach (string s in schemas)
        { // eh, leak 'em. 
            xr = XmlReader.Create(
                new MemoryStream(Encoding.Default.GetBytes(s)));
            xsd.Add(null, xr);
        }
        XDocument doc = new XDocument(element);
        var errored = false;
        doc.Validate(xsd, (o, e) => errored = true);
        if (errored)
            return false;

        // If this doesn't fail, there's an issue with the XSD.
        XNamespace xn = XNamespace.Get(
                      element.GetDefaultNamespace().NamespaceName);
        XElement fail = new XElement(xn + "omgwtflolj/k");
        fail.SetAttributeValue("xmlns", xn.NamespaceName);
        doc = new XDocument(fail);
        var fired = false;
        doc.Validate(xsd, (o, e) => fired = true);
        return fired;
    }

这个将模式作为字符串(程序集中的文件资源)接收,并将它们添加到模式集中。我验证,如果它无效,我返回 false。

如果没有发现 xml 无效,我会进行否定检查以确保我的架构没有搞砸。它不能保证万无一失,但我用它来查找我的模式中的错误。

于 2009-08-14T13:13:18.417 回答
3

更简单的解决方案..

        try
        {
            XmlReaderSettings Xsettings = new XmlReaderSettings();
            Xsettings.Schemas.Add(null, "personDivideSchema.xsd");
            Xsettings.ValidationType = ValidationType.Schema;

            XmlDocument document = new XmlDocument();
            document.Load("person.xml");

            XmlReader reader = XmlReader.Create(new StringReader(document.InnerXml), Xsettings);


            while (reader.Read());
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
        }
于 2009-10-20T06:09:35.270 回答