Convert EDI to XML and vice verse

Converting EDI to XML is seamless by using .NET XML Serializer. All EDI templates are marked for serialization.

public static XDocument Serialize(EdiMessage instance)
{
    if (instance == null)
        throw new ArgumentNullException("instance");

    var serializer = new XmlSerializer(instance.GetType());
    using (var ms = new MemoryStream())
    {
        serializer.Serialize(ms, instance);
        ms.Position = 0;
        return XDocument.Load(ms, LoadOptions.PreserveWhitespace);
    }
}

An XML instance that matches the EDI template structure can also be deserialized to EDI by using the .NET XML Serializer.

public static T Deserialize(XElement xml)
{
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(xml.CreateReader());
}