xml

Deserializing Objects from XML in C#

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 &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;
    }
}

(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.)

Pretty-formatting XML in C#

I had a need to convert an XML string to a nice, indented format. It was a little more complicated than I expected, so I'm posting this snippet here where I can find it again when I need it.

using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;

static string PrettyXml(string xml)
{
    var stringBuilder = new StringBuilder();

    var element = XElement.Parse(xml);

    var settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;
    settings.Indent = true;
    settings.NewLineOnAttributes = true;

    using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
    {
        element.Save(xmlWriter);
    }

    return stringBuilder.ToString();
}

Note that this method can throw exceptions for a variety of reasons.

Syndicate content