questions/47589607/xml-values-with-same-name-to-list

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/47589607/xml-values-with-same-name-to-list


    [XmlRoot(ElementName = "DUE")]
    public class DueDTO
    {
        [XmlAttribute(AttributeName = "idx")]
        public string Idx { get; set; }
        [XmlText]
        public string Text { get; set; }
    }

    [XmlRoot(ElementName = "RATE")]
    public class RateDTO
    {
        [XmlAttribute(AttributeName = "idx")]
        public string Idx { get; set; }
        [XmlText]
        public decimal Text { get; set; }
    }

    [XmlRoot(ElementName = "INVOICE")]
    public partial class InvoicesDTO
    {
        [XmlAttribute(AttributeName = "ID")]
        public string Id { get; set; }
        [XmlElement(ElementName = "STATUS")]
        public string Status { get; set; }
        [XmlElement(ElementName = "TOTAL")]
        public decimal Total { get; set; }

        [XmlElement(ElementName = "DUE")]
        public List<DueDTO> Due { get; set; }
        [XmlElement(ElementName = "RATE")]
        public List<RateDTO> Rate { get; set; }
    }

    public partial class InvoicesDTO
    {
        public InvoicesDueDates[] InvoicesDueDates
        {
            get
            {
                // To make suure we handle cases where only a Rate or Due item of a specific index is present,
                // perform left outer joins with all indices on both Rate and Due.
                // https://docs.microsoft.com/en-us/dotnet/csharp/linq/perform-left-outer-joins
                var query = from i in Due.Select(d => d.Idx).Concat(Rate.Select(r => r.Idx)).Distinct()
                            join due in Due on i equals due.Idx into dueGroup
                            // Throw an exception if we have more than one due item for a given index
                            let due = dueGroup.SingleOrDefault()
                            join rate in Rate on i equals rate.Idx into rateGroup
                            // Throw an exception if we have more than one rate item for a given index
                            let rate = rateGroup.SingleOrDefault()
                            select new InvoicesDueDates { Id = i, DueDate = due == null ? null : due.Text, Rate = rate == null ? (decimal?)null : rate.Text };
                return query.ToArray();
            }
        }
    }


    public class InvoicesDueDates
    {
        public string Id { get; set; }
        public string DueDate { get; set; }
        public decimal? Rate { get; set; }
    }

    public class RootObjectDTO
    {
        [XmlElement("INVOICE")]
        public List<InvoicesDTO> InvoicesDTO { get; set; }
    }

    public class TestClass
    {
        public static void Test()
        {
            var xml = GetXml();

            var root = xml.LoadFromXml<RootObjectDTO>();

            var xml2 = root.GetXml(true);

			Console.WriteLine("\nRe-serialized list of list of all InvoicesDueDates: ");
            Console.WriteLine(root.InvoicesDTO.Select(d => d.InvoicesDueDates).ToArray().GetXml());

			Console.WriteLine("\nRe-serialized {0}", root);
            Console.WriteLine(xml2);
        }

        static string GetXml()
        {
            var xml = @"<RootObjectDTO>
<INVOICE ID=""4"">
    <STATUS>S</STATUS>
    <TOTAL>6230.00</TOTAL>
    <DUE idx=""1"">14.12.17</DUE>
    <RATE idx=""1"">6230.00</RATE>
</INVOICE >
<INVOICE ID=""5"">
    <STATUS>S</STATUS>
    <TOTAL>3270.00</TOTAL>
    <DUE idx=""1"">30.11.17</DUE>
    <RATE idx=""1"">1090.00</RATE>
    <DUE idx=""2"">07.12.17</DUE>
    <RATE idx=""2"">1090.00</RATE>
    <DUE idx=""3"">14.12.17</DUE>
    <RATE idx=""3"">1090.00</RATE>
</INVOICE>
</RootObjectDTO>";
            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));
            T returnValue = default(T);
            using (StringReader reader = new StringReader(xmlString))
            {
                object result = serial.Deserialize(reader);
                if (result is T)
                {
                    returnValue = (T)result;
                }
            }
            return returnValue;
        }

        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("Environment version: " + Environment.Version);
			Console.WriteLine();

			TestClass.Test();
		}
	}
;