Convert Xml String to Object
I Am Receiving Xml Strings over a Socket, and Would Like to Convert These to C# Objects. the Messages Are of the Form: 1 Stop I Am New To. Net, and Am Not Sure...
I am receiving XML strings over a socket, and would like to convert these to C# objects.
The messages are of the form:
<msg>
<id>1</id>
<action>stop</action>
</msg>
I am new to .Net, and am not sure the best practice for performing this. I've used JAXB for Java before, and wasn't sure if there is something similar, or if this would be handled a different way.
15 Answers
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.
Must Read
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 ToolsOr 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