如何通过.NET验证xml代码文件?+如果我使用XML序列化怎么办? [英] How to validate xml code file though .NET? + How would I do it if I use XML serialization?

查看:59
本文介绍了如何通过.NET验证xml代码文件?+如果我使用XML序列化怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户能够将数据导出为XML文件.当然,我希望他们以后能够导入相同的XML文件,但是他们总是可以更改它,也可以是其他XML文件.

I want users to be able to export data as an XML file. Of course I want them to be able to later on import that same XML file however they always could change it or it could be a different XML file.

因此,我想验证XML文件以检查其格式是否符合我的期望.因此,我想我需要一个类似架构的东西来检查它是否必须通过代码来完成.

So I want to validate the XML file to check if it is in the format that I expect. So I guess I would need something like a schema to check just that it has to be through code.

所以我希望

<Root>
 <Something>
    <SomethingElse> </SomethingElse>
 </Something>
</Root>

除了我期望的格式之外,我不希望其他格式存在于文件中.

I don't want some other format to be in the file other then the one I expect.

我还将如何验证字段?就像我说的那样,我要求标记之间必须有一些文本.如果为空,则文件无效.

Also how would I validate fields? Like say I require that there must be some text in between tags. If it is blank the file is not valid.

那我该怎么办呢?

修改

我决定使用XML序列化,因此我知道如果格式错误,它将通过异常处理,并忽略不起作用的内容.但是我不确定我应该只是通过它和C#来验证每条记录,还是应该尝试创建一个xml模式来做到这一点.

I decided to use XML serialization so I know it will through an exception if it is the wrong format and ignore stuff that does not work. However I am not sure should I just go through it and C# to validate each of the records or should I try to make an xml schema to do it.

如果我想通过带有xml序列化的xml模式进行操作,那将如何工作?就像我先做一些我在响应中看到的事情,然后反序列化它吗?还是我会怎么做?

If I would want to do it through an xml schema with xml serialization how would that work? Like Do I first do something like I seen in the responses then de serialize it? Or how would I do it?

推荐答案

以下是您可以用来实现的代码段:

Here's a code snippet that you can use to do so:

using (FileStream stream = File.OpenRead(xsdFilepath))
{
    XmlReaderSettings settings = new XmlReaderSettings();

    XmlSchema schema = XmlSchema.Read(stream, OnXsdSyntaxError);
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add(schema);
    settings.ValidationEventHandler += OnXmlSyntaxError;

    using (XmlReader validator = XmlReader.Create(xmlPath, settings))
    {
        // Validate the entire xml file
        while (validator.Read()) ;
    }
}

发生语法错误时,将调用OnXmlSyntaxError函数.

The OnXmlSyntaxError function will be called when a syntax error occur.

这篇关于如何通过.NET验证xml代码文件?+如果我使用XML序列化怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆