简体   繁体   中英

c# how to create a typed dataset from a dataset or a XML file?

I have XML file that I can easily load into a dataset.

    DataSet ds = new DataSet();
    ds.ReadXml(e.FullPath);

However, I did like to have a typed dataset instead.
Is there a way to build the typed dataset from the XML or the untyped dataset?

The goal here is to avoid design it because there is a lot of column and it remove the change of making mistake while typing.

It is really easy to do. Here is a step by step guide.
(You must have visual studio installed of course)

1. From the XML File, create a XSD File.

This can be acheived by loading the XML file into a dataset and then writing the schema. The following code take care of this step.

        DataSet ds = new DataSet();   
        ds.ReadXml(e.FullPath);   
        ds.WriteXml(@"C:\test.xsd", XmlWriteMode.WriteSchema);

Verify the XSD file is good and doesn't contains junk.

2. Locate where "xsd.exe" is on your computer.
In my case, it was here :
C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.0A\\bin\\NETFX 4.0 Tools

3. Copy/paste the xsd file into the folder found at step2.

4. Run command prompt and change directory to folder found at step2.

Open a command prompt (Windows+R, type "cmd" and hit enter). Then navigate to the folder found at step2. ("cd enter-your-directory-here")

    cd C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools  

Quick tips, you can copy/paste the directory into the prompt using the mouse's right click.

5. From the command prompt, launch xsd.exe with desired argument.
Type or paste the following command in the command prompt and press enter.

    xsd.exe /d /l:cs test.xsd /eld /n:MyDesiredNameSpace  

If needed, you can find details about arguments in msdn documentation.

Given your xsd file was valid, it will output a cs file into the folder. Here is what console output.

命令输出

6. Include the generated file into your project.
Copy and paste the generated .cs file into your solution folder and include it to your project. Using (right-click include existing item)
将文件包含到项目中

7. Rename the typed dataset with an appropriate name.
The generated typed dataset is "NewDataset".
Rename it for a more decent name. (use refactor feature) 重命名类型化的数据集

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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