xmlserializer 验证

发布于 2024-08-11 01:21:30 字数 140 浏览 4 评论 0原文

我正在使用 XmlSerializer 反序列化 Xml 档案。但我发现生成的类 xsd.exe 仅提供读取 xml 的功能,但没有验证。例如,如果文档中缺少一个节点,则生成的类的属性字段将为 null,而不是像我预期的那样抛出验证异常。我怎样才能做到这一点?谢谢!

I'm using XmlSerializer to deserialize Xml achives. But I found the class xsd.exe generated only offers capability to read the xml, but no validation. For example, if one node is missing in a document, the attribute field of the generated class will be null, rather than throws a validation exception as I expected. How can I achieve that? Thanks!

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

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

发布评论

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

评论(2

羞稚 2024-08-18 01:21:30

以下代码应在反序列化时针对架构进行验证。类似的代码可用于在序列化时针对模式进行验证。

private static Response DeserializeAndValidate(string tempFileName)
{
    XmlSchemaSet schemas = new XmlSchemaSet();
    schemas.Add(LoadSchema());

    Exception firstException = null;

    var settings = new XmlReaderSettings
                   {
                       Schemas = schemas,
                       ValidationType = ValidationType.Schema,
                       ValidationFlags =
                           XmlSchemaValidationFlags.ProcessIdentityConstraints |
                           XmlSchemaValidationFlags.ReportValidationWarnings
                   };
    settings.ValidationEventHandler +=
        delegate(object sender, ValidationEventArgs args)
        {
            if (args.Severity == XmlSeverityType.Warning)
            {
                Console.WriteLine(args.Message);
            }
            else
            {
                if (firstException == null)
                {
                    firstException = args.Exception;
                }

                Console.WriteLine(args.Exception.ToString());
            }
        };

    Response result;
    using (var input = new StreamReader(tempFileName))
    {
        using (XmlReader reader = XmlReader.Create(input, settings))
        {
            XmlSerializer ser = new XmlSerializer(typeof (Response));
            result = (Response) ser.Deserialize(reader);
        }
    }

    if (firstException != null)
    {
        throw firstException;
    }

    return result;
}

The following code should validate against a schema while deserializing. Similar code can be used to validate against a schema while serializing.

private static Response DeserializeAndValidate(string tempFileName)
{
    XmlSchemaSet schemas = new XmlSchemaSet();
    schemas.Add(LoadSchema());

    Exception firstException = null;

    var settings = new XmlReaderSettings
                   {
                       Schemas = schemas,
                       ValidationType = ValidationType.Schema,
                       ValidationFlags =
                           XmlSchemaValidationFlags.ProcessIdentityConstraints |
                           XmlSchemaValidationFlags.ReportValidationWarnings
                   };
    settings.ValidationEventHandler +=
        delegate(object sender, ValidationEventArgs args)
        {
            if (args.Severity == XmlSeverityType.Warning)
            {
                Console.WriteLine(args.Message);
            }
            else
            {
                if (firstException == null)
                {
                    firstException = args.Exception;
                }

                Console.WriteLine(args.Exception.ToString());
            }
        };

    Response result;
    using (var input = new StreamReader(tempFileName))
    {
        using (XmlReader reader = XmlReader.Create(input, settings))
        {
            XmlSerializer ser = new XmlSerializer(typeof (Response));
            result = (Response) ser.Deserialize(reader);
        }
    }

    if (firstException != null)
    {
        throw firstException;
    }

    return result;
}
£烟消云散 2024-08-18 01:21:30

以下代码将以编程方式根据架构文件手动加载和验证 XML,从而允许您处理任何 导致错误和/或警告

//Read in the schema document
using (XmlReader schemaReader = XmlReader.Create("schema.xsd"))
{
    XmlSchemaSet schemaSet = new XmlSchemaSet();

    //add the schema to the schema set
    schemaSet.Add(XmlSchema.Read(schemaReader, 
    new ValidationEventHandler(
        delegate(Object sender, ValidationEventArgs e)
        {
        }    
    )));

    //Load and validate against the programmatic schema set
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Schemas = schemaSet;
    xmlDocument.Load("something.xml");

    xmlDocument.Validate(new ValidationEventHandler(
        delegate(Object sender, ValidationEventArgs e)
        {
            //Report or respond to the error/warning
        }
    )); 
 }

现在显然您希望 xsd.exe 生成的类在加载时自动执行此操作(上述方法需要对 XML 文件进行第二次处理),但预加载验证将允许您以编程方式检测格式错误的输入文件。

The following code will manually load and validate your XML against a schema file programmatically, allowing you to deal with any resulting errors and/or warnings.

//Read in the schema document
using (XmlReader schemaReader = XmlReader.Create("schema.xsd"))
{
    XmlSchemaSet schemaSet = new XmlSchemaSet();

    //add the schema to the schema set
    schemaSet.Add(XmlSchema.Read(schemaReader, 
    new ValidationEventHandler(
        delegate(Object sender, ValidationEventArgs e)
        {
        }    
    )));

    //Load and validate against the programmatic schema set
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Schemas = schemaSet;
    xmlDocument.Load("something.xml");

    xmlDocument.Validate(new ValidationEventHandler(
        delegate(Object sender, ValidationEventArgs e)
        {
            //Report or respond to the error/warning
        }
    )); 
 }

Now obviously you desire to have the classes generated by xsd.exe to do this automatically and while loading (the above approach would require a second handling of the XML file), but a pre-load validate would allow you to programmatically detect a malformed input file.

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