Convert XML String to Object
You need to use the xsd.exe
tool which gets installed with the Windows SDK into a directory something similar to:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
And on 64-bit computers:
C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin
And on Windows 10 computers:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin
On the first run, you use xsd.exe
and you convert your sample XML into a XSD file (XML schema file):
xsd yourfile.xml
This gives you yourfile.xsd
, which in a second step, you can convert again using xsd.exe
into a C# class:
xsd yourfile.xsd /c
This should give you a file yourfile.cs
which will contain a C# class that you can use to deserialize the XML file you're getting - something like:
XmlSerializer serializer = new XmlSerializer(typeof(msg));msg resultingMessage = (msg)serializer.Deserialize(new XmlTextReader("yourfile.xml"));
Should work pretty well for most cases.
Update: the XML serializer will take any stream as its input - either a file or a memory stream will be fine:
XmlSerializer serializer = new XmlSerializer(typeof(msg));MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));msg resultingMessage = (msg)serializer.Deserialize(memStream);
or use a StringReader:
XmlSerializer serializer = new XmlSerializer(typeof(msg));StringReader rdr = new StringReader(inputString);msg resultingMessage = (msg)serializer.Deserialize(rdr);
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+ with .Net Framework >= 4.5 as project target and 'Windows Communication Foundation' individual component installed
- 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.Extensionsusing 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(@"D:\file.xml"); var catalog1 = xml.ParseXML<catalog>(); string json = File.ReadAllText(@"D:\file.json"); var catalog2 = json.ParseJSON<JSONRoot>();
Try this method to Convert Xml to an object. It is made for exactly what you are doing:
protected T FromXml<T>(String xml){ T returnedXmlClass = default(T); try { using (TextReader reader = new StringReader(xml)) { try { returnedXmlClass = (T)new XmlSerializer(typeof(T)).Deserialize(reader); } catch (InvalidOperationException) { // String passed is not XML, simply return defaultXmlClass } } } catch (Exception ex) { } return returnedXmlClass ; }
Call it using this code:
YourStrongTypedEntity entity = FromXml<YourStrongTypedEntity>(YourMsgString);