可以在运行时使用代码针对 xsd 验证 xml 吗?

发布于 2024-08-02 02:23:43 字数 55 浏览 7 评论 0原文

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

I have xml files that I read in at runtime, is is possible to validate the xml against an xsd file at runtime? using c#

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤独陪着我 2024-08-09 02:23:43

尝试这个:

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

Try this:

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);
}
心清如水 2024-08-09 02:23:43

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

    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 无效,我会进行否定检查以确保我的架构没有搞砸。 它不能保证万无一失,但我已经用它来查找我的模式中的错误。

I GOT CODE TOO! I use this in my tests:

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

This one takes in the schemas as strings (file resources within the assembly) and adds them to a schema set. I validate and if its not valid I return false.

If the xml isn't found to be invalid, I do a negative check to make sure my schemas aren't screwed up. Its not guaranteed foolproof, but I have used this to find errors in my schemas.

可是我不能没有你 2024-08-09 02:23:43

更简单的解决方案..

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

simpler solution..

        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());
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文