简体   繁体   English

从XML模式进行C#数据集验证

[英]C# DataSet validation from XML schema

I have a xml schema. 我有一个XML模式。 I want to populate a DataSet and validate it using this schema. 我想填充一个数据集并使用此架构对其进行验证。

DataSet package = new DataSet();
StringReader schemaResourceReader = new StringReader(PackageValidationLibrary.Properties.Resources.myPackage);
package.ReadXmlSchema(schemaResourceReader);


package.Tables["Table1"].Rows.Add(packageDetail.date,packageDetail.code,packageDetail.amount,packageDetail.place,"0");
package.Tables["Table2"].Rows.Add("0","0");
foreach (Cek data in recordList){
    package.Tables["Table3"].Rows.Add(data.Serial, data.Code, data.Branch, data.ValidityDate, "0");
}

Using the code above I can load data but I cannot validate it although dataset imports the schema. 使用上面的代码,我可以加载数据,但是尽管数据集导入了架构,但我无法对其进行验证。

I tried to get xml string using package.GetXml() method and reload the xml again. 我尝试使用package.GetXml()方法获取xml字符串,然后再次重新加载xml。 Then I got exceptions. 然后我得到了例外。

How can I validate this table? 如何验证此表? Thanks. 谢谢。


EDIT As I understand from answers and comments it is not possible to validate while populating the dataset. 编辑据我从答案和评论中了解到,在填充数据集时无法进行验证。 Then I read the xml from dataset and loaded it with the configuration given below. 然后,我从数据集中读取xml,并使用下面给出的配置将其加载。

_schema = XmlSchema.Read(new StringReader(PackageValidationLibrary.Properties.Resources.TakasPaketi), new ValidationEventHandler(ValidationEventHandler));
                XmlReaderSettings _settings = new XmlReaderSettings();
                _settings.Schemas.Add(_schema);
                _settings.ValidationType = ValidationType.Schema;
                XmlReader vreader = XmlReader.Create(stream, _settings);

I believe this will do it: 我相信这可以做到:

    // First, read in the XML schema
    DataSet MyDataSet = new DataSet();
    MyDataSet.ReadXmlSchema(@"C:\YourSchema.xsd");


    // Now, read in the XML file (it is validated 
    // against the schema when it is read in).
    MyDataSet.ReadXml(@"C:\YourFile.xml");

If you edit the data xml file to not match the schema, an exception will be thrown when the xml file is read. 如果您将数据xml文件编辑为与架构不匹配,则在读取xml文件时将引发异常。

So in your case you may have to export the dataset to an xml string and then read it back in. You say you are getting exceptions when you do this....what exceptions? 因此,在您的情况下,您可能必须将数据集导出到xml字符串,然后再读回。您说这样做时会得到异常。...什么异常? Maybe the data isn't valid for the schema you have. 可能数据对于您拥有的架构无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM