Thursday, 9 May 2013

Generate class from xml

Using XML Schema Definition Tool (Xsd.exe)

I needed to write code that maps data in xml to my cs file.
I know that that xsd can generate this.

Lets do it step by step.

Generate definition file


C:\test\1>xsd AttachFileHandler.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\test\1\AttachFileHandler.xsd'.




Generate class: 

c:\test\1>xsd /classes /language:CS AttachFileHandler.xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'c:\test\1\AttachFileHandler.cs'.


Generate dataset

C:\test\1>xsd /dataset /language:CS AttachFileHandler.xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\test\1\AttachFileHandler.cs'.


 Final result



C:\test\1>dir

 Directory of C:\test\1

09/05/2013  12:11    <DIR>          .
09/05/2013  12:11    <DIR>          ..
09/05/2013  12:11           468,262 AttachFileHandler.cs
09/05/2013  12:05             2,746 AttachFileHandler.xml
09/05/2013  12:11             8,374 AttachFileHandler.xsd


Result => just extract of generated data

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18034
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.0.30319.17929.

//


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Statistics {
    }



For more help see following location:

http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx tool