questions/47641622/serialize-parallel-arrays-to-xml-in-c-sharp-in-a-specific-order

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Threading;
using System.ComponentModel;
using System.Xml.Linq;
using System.Reflection;
using System.Data;
using System.Xml.Schema;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml.XPath;
using System.Globalization;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;

    // https://stackoverflow.com/questions/47641622/serialize-parallel-arrays-to-xml-in-c-sharp-in-a-specific-order

    public partial class PartList
    {
        [XmlIgnore]
		public List<string> Name { get; } = new List<string>();

        [XmlIgnore]
		public List<string> Data { get; } = new List<string>();

        [XmlIgnore]
        public List<string> OtherData { get; } = new List<string>();

        [System.Xml.Serialization.XmlElementAttribute("Name", typeof(Name), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        [System.Xml.Serialization.XmlElementAttribute("Data", typeof(Data), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        [System.Xml.Serialization.XmlElementAttribute("OtherData", typeof(OtherData), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public ValueWrapper<string>[] Values
        {
            get
            {
                var list = new List<ValueWrapper<string>>();
                for (int i = 0, count = Math.Max(Name.Count, Math.Max(Data.Count, OtherData.Count)); i < count; i++)
                {
                    if (i < Name.Count)
                        list.Add(new Name { Value = Name[i] });
                    if (i < Data.Count)
                        list.Add(new Data { Value = Data[i] });
                    if (i < OtherData.Count)
                        list.Add(new OtherData { Value = OtherData[i] });
                }
                return list.ToArray();
            }
            set
            {
                if (value == null)
                    return;
                Name.AddRange(value.OfType<Name>().Select(v => v.Value));
                Data.AddRange(value.OfType<Data>().Select(v => v.Value));
                OtherData.AddRange(value.OfType<OtherData>().Select(v => v.Value));
            }
        }
    }

    public class Name : ValueWrapper<string> { }

    public class Data : ValueWrapper<string> { }

    public class OtherData : ValueWrapper<string> { }

    public abstract class ValueWrapper<T> : ValueWrapper where T : IConvertible
    {
        public override object GetValue() => Value; 
		
        [XmlText]
        public T Value { get; set; }
    }

    public abstract class ValueWrapper
    {
        public abstract object GetValue();
    }

    [XmlRoot("Part", Namespace = "")]
    public class Part
    {
        public PartList List { get; set; }
    }

    class TestClass
    {
        public static void Test()
        {
            var part = new Part
            {
                List = new PartList
                {
                    Name = { "Some Test", "Other Lama" },
                    Data = { "123131313", "331331313" },
                    OtherData = { "0.11", "0.02" },
                }
            };

            var xml = part.GetXml(true);

            Console.WriteLine("\nInitially serialized {0}", part);
            Console.WriteLine(xml);

            var part2 = xml.LoadFromXml<Part>();

            var xml2 = part.GetXml(true);

            Console.WriteLine("\nDeserialized and re-serialized {0}", part);
            Console.WriteLine(xml2);

            Assert.IsTrue(XNode.DeepEquals(XElement.Parse(xml), XElement.Parse(xml2)));
            Assert.IsTrue(XNode.DeepEquals(XElement.Parse(xml), XElement.Parse(GetDesiredXml())));
            Console.WriteLine("\nActual and expected XML are equivalent.");
        }

        static string GetDesiredXml()
        {
            var xml = @"<Part>
    <List>
        <Name>Some Test</Name>
        <Data>123131313</Data>
        <OtherData>0.11</OtherData>
        <Name>Other Lama</Name>
        <Data>331331313</Data>
        <OtherData>0.02</OtherData>
    </List>
</Part>";
            return xml;
        }
    }

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }

    public static class XmlSerializationHelper
    {
        public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
        {
            serial = serial ?? new XmlSerializer(typeof(T));
            using (var reader = new StringReader(xmlString))
            {
				return (T)serial.Deserialize(reader);
            }
        }

        public static string GetXml<T>(this T obj, bool omitStandardNamespaces)
        {
			return obj.GetXml(null, omitStandardNamespaces);
        }
		
        public static string GetXml<T>(this T obj, XmlSerializer serializer = null, bool omitStandardNamespaces = false)
        {
            XmlSerializerNamespaces ns = null;
            if (omitStandardNamespaces)
            {
                ns = new XmlSerializerNamespaces();
                ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
            }			
            using (var textWriter = new StringWriter())
            {
                var settings = new XmlWriterSettings() { Indent = true }; // For cosmetic purposes.
                using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                    (serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
                return textWriter.ToString();
            }
        }
    }
										
	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Uncaught exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;