C# Typed Xml Parsing

Date: 2019-11-12

Generate classes from XML by:

  • Copying the available XML to clipboard
  • In Visual Studio select in menu Edit
  • Paste special > Paste as XML classes
  • Cleanup classes, adjust types + Add Attributes (XmlRoot, XmlType, XmlElement, XmlArray, XmlAttribute)
using System;
using System.ComponentModel;
using System.Xml.Serialization;

namespace Models
{
    [Serializable]
    [DesignerCategory("code")]
    [XmlType(AnonymousType = true)]
    //[XmlRoot("NewGroupName")] // xml root element
    //[XmlType("NewTypeName")] // xml schema
    public class MessagesMessage
    {
        [XmlElement("MessageStandard")]
        public string MessageStandard { get; set; }
        public byte MessageType { get; set; }
        public string MessageDate { get; set; }
        public string IsTestMessage { get; set; }
        public string OrderNumberBuyer { get; set; }
        public string IsNormalOrder { get; set; }
        public string IsCrossdock { get; set; }
        public string IsAcknowledgementRequested { get; set; }
        public ulong BuyerGLN { get; set; }
        public string SupplierGLN { get; set; }
        public ulong DeliveryPartyGLN { get; set; }
        public string ShipFromPartyGLN { get; set; }
        public string UltimateConsigneeGLN { get; set; }
        public ulong InvoiceeGLN { get; set; }
        public string IsDutyFree { get; set; }
        public string IsBackhauling { get; set; }
        public ulong MessageReference { get; set; }
        [XmlElement("Article")]
        public MessagesMessageArticle[] Article { get; set; }
    }
	
	public class XmlHelper
	{
		public static T ParseXML<T>(string xml) where T : class
        {
            using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml.Trim())))
            {
                var reader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
                return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
            }
        }
		
		public static void Example() 
		{
			var message = TransusApi.ParseXML<MessagesMessage>(ExampleOrderMessage());
		}
	}
}
using System.Xml;
using System.Xml.Serialization;

public static T ParseXML<T>(string xml) where T : class
{
    try
    {
        if (string.IsNullOrWhiteSpace(xml))
            return null;

        using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml.Trim())))
        {
            var reader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
            return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
        }
    }
    catch (InvalidOperationException)
    {
        return null;
    }
}

public static string SerializeXML<T>(T obj) where T : class
{
    using (var stream = new MemoryStream())
    using (var reader = new StreamReader(stream))
    {
        new XmlSerializer(typeof(T)).Serialize(stream, obj);
        stream.Position = 0;
        return reader.ReadToEnd();
    }
}
28400cookie-checkC# Typed Xml Parsing