Here's another C# code snippet that takes me way too much time to recreate by just reading the documentation.
This is a simple example of a class that can be serialized to/from XML. In this case the "ServerConfig" XML string can contain a list of servers, looking like this:
<ServerConfig loggingEnabled="1">
<Servers>
<Server host="test1.example.com" port="9999" />
<Server host="test2.example.com" port="8888" />
</Servers>
</ServerConfig>
The client code can just do "var serverConfig = ServerConfig.FromXmlString(s);" to deserialize it into a ServerConfig object.
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;
}
}
(The method that would serialize a ServerConfig to an XML string is left as an exercise for the reader. I rarely need to do that.)