Generate C# class from XML
Yes, by using xsd.exe
D:\temp>xsd test.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'D:\temp\test.xsd'.
D:\temp>xsd test.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'D:\temp\test.cs'.
Notes
Answer how to change directory in Developer Command Prompt to d:\temp may be useful.
If you generate classes for multi-dimensional array, there is a bug in XSD.exe generator, but there are workarounds.
How to convert XML/JSON file to C# class?
You have two possibilities.
Method 1. XSD tool
Suppose that you have your XML file in this location
C:\path\to\xml\file.xml
- Open Developer Command Prompt
You can find it inStart Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools
Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen - Change location to your XML file directory by typing
cd /D "C:\path\to\xml"
- Create XSD file from your xml file by typing
xsd file.xml
- Create C# classes by typing
xsd /c file.xsd
And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs
Method 2 - Paste special
Required Visual Studio 2012+
- Copy content of your XML file to clipboard
- Add to your solution new, empty class file (Shift+Alt+C)
- Open that file and in menu click
Edit > Paste special > Paste XML As Classes
And that's it!
Usage
Usage is very simple with this helper class:
using System;
using System.IO;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
using System.Xml;
using System.Xml.Serialization;
namespace Helpers
{
internal static class ParseHelpers
{
private static JavaScriptSerializer json;
private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }
public static Stream ToStream(this string @this)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(@this);
writer.Flush();
stream.Position = 0;
return stream;
}
public static T ParseXML<T>(this string @this) where T : class
{
var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
}
public static T ParseJSON<T>(this string @this) where T : class
{
return JSON.Deserialize<T>(@this.Trim());
}
}
}
All you have to do now, is:
public class JSONRoot
{
public catalog catalog { get; set; }
}
// ...
string xml = File.ReadAllText(@"C:\path\to\xml\file.xml");
var catalog1 = xml.ParseXML<catalog>();
string json = File.ReadAllText(@"C:\path\to\json\file.json");
var catalog2 = json.ParseJSON<JSONRoot>();
Here you have some Online XML <--> JSON
Converters: Click
generate xml files based on my c# classes
Create following classes to hold your data and validate it:
public class Community
{
public string Author { get; set; }
public int CommunityId { get; set; }
public string Name { get; set; }
[XmlArray]
[XmlArrayItem(typeof(RegisteredAddress))]
[XmlArrayItem(typeof(TradingAddress))]
public List<Address> Addresses { get; set; }
}
public class Address
{
private string _postCode;
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PostCode
{
get { return _postCode; }
set {
// validate post code e.g. with RegEx
_postCode = value;
}
}
}
public class RegisteredAddress : Address { }
public class TradingAddress : Address { }
And serialize that instance of community class to xml:
Community community = new Community {
Author = "xxx xxx",
CommunityId = 0,
Name = "name of community",
Addresses = new List<Address> {
new RegisteredAddress {
AddressLine1 = "xxx",
AddressLine2 = "xxx",
AddressLine3 = "xxx",
City = "xx",
Country = "xxxx",
PostCode = "0000-00"
},
new TradingAddress {
AddressLine1 = "zz",
AddressLine2 = "xxx"
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Community));
serializer.Serialize(File.Create("file.xml"), community);
I think a little googling will help you to understand how to deserialize community object back from file.
How to convert complex XML to .NET Class?
give a try to the XSD.exe tool shipped with Visual Studio.
Here's some docs:
http://www.codeproject.com/Articles/11317/From-XML-to-Strong-Types-in-C
Generating C# classes based on XML request using ArrayOfString
Since you don't have a WSDL file for the service, what you can do use the little known feature of Visual Studio which Paste XML as Class that uses class generation features introduced in .NET 4.5.
The steps to use this feature are:
- Create Class file that the XML to be inserted into.
- With the cursor inside the class file, click Edit -> Paste Special -> Paste XML as Classes.
Visual Studio will then populate the class file with the generated classes for your XML request.
Note: Your example XML is currently malformed the xmlns:tem
attribute is not closed on the envelope element. This feature will not work if the XML is malformed.
Generating C# class from XML or XSD programatically
After all I managed to write a generic .bat file which calls xsd.exe upon all needed xsds like so
for /R %%f in (*.xsd) do (
xsd /c "%%f" /outputdir:..\Objects /n:DataSource.Main.xsd.Objects)
and run this file programatically. The only con of this solution is that you need to add xsd.exe to your PATH.
how to create c# class from Xsd
On Windows, there's a Microsoft program called xsd.exe that will turn your XML into a schema (XSD), and generate C# classes from that. It's installed with Visual Studio on Windows. It's in C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools or similar, although if you start a Visual Studio Developer Command Prompt it will be on the path. To use it with your file:
- Save the XML data as data.xml or similar (it's XML not an XSD clearly)
- The tool doesn't like the fact that 'interface' has both an attribute called 'id' and an element called 'id', so rename one of them or take one out.
To generate an XSD file called data.xsd: start a Developer Command prompt then navigate to the folder with data.xml in and do:
xsd data.xml
To generate C# classes in a file called data.cs do:
xsd /c data.xsd
The resulting classes are serializable, so you can deserialize the XML into them.
The drawback of doing it this way is the classes you get are complex (I'm getting 340 lines of code with your XML!), so crafting your classes by hand may be better.
I wrote about this (a long long time ago) with respect to the very complex FpML schemas.
Related Topics
Difference Between the | and || or Operators
Graph Nodes Coordinates Evaluation
How to Do a Deep Copy of an Object in .Net
Possible to Call C++ Code from C#
Using a Class Defined in a C++ Dll in C# Code
How to Convert a Byte Array to a Hexadecimal String, and Vice Versa
Serialize and Deserialize Json and Json Array in Unity
What Does Void Mean in C, C++, and C#
Post a Form Array Without Successful
How to Strip HTML Tags from a String in Asp.Net
Convert a String to an Enum in C#
Understanding Garbage Collection in .Net
Convert Generic List/Enumerable to Datatable
Cs0120: an Object Reference Is Required For the Nonstatic Field, Method, or Property 'Foo'