Created
August 1, 2012 14:48
-
-
Save kristopherjohnson/3227483 to your computer and use it in GitHub Desktop.
C# snippet: Example of deserializing XML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 <ServerConfig> 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See http://undefinedvalue.com/2011/11/22/deserializing-objects-xml-c for details of what this does and how to use it.