Load xml schema and data into DataSet (and datagridview)

16,182

Make it an embedded strongly-typed resource.

Add the file to your project and give it a Build Action of "Content", and "Do Not Copy". Then open up the Resources designer tab (either from the Properties folder, or in the Project Properties dialog) and drag the file onto the Resource Designer canvas. The file is now embedded into your assembly. This will produce a strongly-typed property of the default Resources class, with the same name as the file it came from.

To load it into the data set you can hook up a StringReader to it. Note that you almost always want to load the schema first, as it changes the behavior of ReadXml:

var ds = new DataSet();
using (var rdr = new StringReader(Properties.Resources.myschema))
{
    ds.ReadXmlSchema(rdr);
}
ds.ReadXml("mystuff.xml", XmlReadMode.IgnoreSchema);

For XmlReadMode you have a couple of options. They dictate what happens if your data doesn't match your schema, and what to do if there's a schema defined inline in the XML file that differs from the one you already loaded:

  • XmlReadMode.ReadSchema will import any inline schema as long as it doesn't collide with the already-loaded schema; if there are name collisions, the ReadXml will throw; or
  • XmlReadMode.IgnoreSchema will ignore any inline schema, and try to force the data to the schema you specified. In this mode, data that doesn't match your schema will not end up in the dataset.
  • XmlReadMode.InferSchema will ignore any inline schema, but in this case, any data that doesn't conform to your schema will cause your schema to be extended; for example, if your XML file has a table that isn't in your schema, that table will get added to your schema and the data imported. If there are name collisions between columns of different types, ReadXml will throw;

If you do the ReadXml first, you always get ReadSchema mode if there's an inline schema, or InferSchema mode if there isn't. Even if that's what you want it's better to be explicit about it.

Share:
16,182
akevan
Author by

akevan

Updated on June 04, 2022

Comments

  • akevan
    akevan almost 2 years

    I have a datagridview populated with data from an .xml file. The data is a list of MyObjects, where MyObject is a C# class I have. This initially was done without a schema, so no type information :( Means I don't get the benefit of auto-generated checkbox columns for bools, etc. in the MyObject class.

    So I used xsd.exe to generate an .xsd file. Looks great! But how do I deploy this .xsd with the app? Do I have to make sure it sits in the same directory as my app and load it like:

    DataSet ds = new DataSet();
    ds.ReadXml("mystuff.xml");
    ds.ReadXmlSchema("myschema.xsd");
    dataGridView_1.DataSource = ds;
    dataGridView_1.DataMember = "MyObject";
    

    I'm sure there's a better way to handle this... can I include it as part of the assembly or something? Thanks for any help.