Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created August 1, 2012 14:48
Show Gist options
  • Save kristopherjohnson/3227483 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/3227483 to your computer and use it in GitHub Desktop.
C# snippet: Example of deserializing XML
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
public sealed class ServerConfig
{
public sealed class Server
{
[XmlAttribute("host")]
public string Host { get; set; }
[XmlAttribute("port")]
public int Port { get; set; }
public Server()
{
host = "";
port = 0;
}
}
[XmlArray]
public Server[] Servers { get; set; }
[XmlAttribute("loggingEnabled")]
public int LoggingEnabled { get; set; }
public ServerConfig()
{
Servers = null;
LoggingEnabled = 0;
}
/// <summary>
/// Create an instance of ServerConfig from an XML string
/// </summary>
/// <param name="xmlString">XML string containing &lt;ServerConfig&gt; element</param>
/// <returns>ServerConfig instance</returns>
/// <remarks>
/// Throws an exception if the XML string is not valid.
/// </remarks>
public static ServerConfig FromXmlString(string xmlString)
{
var reader = new StringReader(xmlString);
var serializer = new XmlSerializer(typeof(ServerConfig));
var instance = (ServerConfig) serializer.Deserialize(reader);
return instance;
}
}
@kristopherjohnson
Copy link
Author

See http://undefinedvalue.com/2011/11/22/deserializing-objects-xml-c for details of what this does and how to use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment