questions/42114531/populating-any-elements-on-a-web-service-in-c-sharp

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;

namespace Question42114531.V1
{
    // https://stackoverflow.com/questions/42114531/populating-any-elements-on-a-web-service-in-c-sharp
    [XmlRoot(ElementName = "Address")]
    public class Address
    {
        [XmlElement(ElementName = "Street1")]
        public string Street1 { get; set; }
        [XmlElement(ElementName = "City")]
        public string City { get; set; }
        [XmlElement(ElementName = "State")]
        public string State { get; set; }
        [XmlElement(ElementName = "Postal")]
        public string Postal { get; set; }
    }

    [XmlRoot(ElementName = "Contact")]
    public class Contact
    {
        [XmlElement(ElementName = "Name")]
        public string Name { get; set; }
        [XmlElement(ElementName = "Phone")]
        public string Phone { get; set; }
        [XmlElement(ElementName = "Address")]
        public Address Address { get; set; }
    }

    [XmlRoot(ElementName = "Contacts")]
    public class Contacts
    {
        [XmlElement(ElementName = "Contact")]
        public Contact Contact { get; set; }
    }

    [XmlRoot("GenericRequestData_Type")]
    public class Person
    {
        public string Name { get; set; }
        public DateTime BirthDate { get; set; }
        [XmlArray("Emails")]
        [XmlArrayItem("Email")]
        public List<string> Emails { get; set; }
        [XmlArray("Issues")]
        [XmlArrayItem("Id")]
        public List<long> IssueIds { get; set; }
    }

    public class GenericRequestData_Type
    {
        private System.Xml.XmlElement[] anyField;

        [System.Xml.Serialization.XmlAnyElementAttribute()]
        public System.Xml.XmlElement[] Any
        {
            get
            {
                return this.anyField;
            }
            set
            {
                this.anyField = value;
            }
        }
    }

    static class TestClass
    {
        internal static void Test()
        {
            var genericRequest = new GenericRequestData_Type();

            var contacts = new Contacts
            {
                Contact = new Contact
                {
                    Name = "Patrick Hines",
                    Phone = "206-555-0144",
                    Address = new Address
                    {
                        Street1 = "123 Main St",
                        City = "Mercer Island",
                        State = "WA",
                        Postal = "68042",
                    },
                }
            };
            genericRequest.Any = new[] { contacts.AsXmlElement() };

            Console.WriteLine(genericRequest.GetXml());
        }
    }

    public static class XmlNodeExtensions
    {
        public static XmlDocument AsXmlDocument<T>(this T o, XmlSerializerNamespaces ns = null, XmlSerializer serializer = null)
        {
            XmlDocument doc = new XmlDocument();
            using (XmlWriter writer = doc.CreateNavigator().AppendChild())
                new XmlSerializer(o.GetType()).Serialize(writer, o, ns ?? NoStandardXmlNamespaces());
            return doc;
        }

        public static XmlElement AsXmlElement<T>(this T o, XmlSerializerNamespaces ns = null, XmlSerializer serializer = null)
        {
            return o.AsXmlDocument(ns, serializer).DocumentElement;
        }

        public static T Deserialize<T>(this XmlElement element, XmlSerializer serializer = null)
        {
            using (var reader = new ProperXmlNodeReader(element))
                return (T)(serializer ?? new XmlSerializer(typeof(T))).Deserialize(reader);
        }
		
        /// <summary>
        /// Return an XmlSerializerNamespaces that disables the default xmlns:xsi and xmlns:xsd lines.
        /// </summary>
        /// <returns></returns>
        public static XmlSerializerNamespaces NoStandardXmlNamespaces()
        {
            var ns = new XmlSerializerNamespaces();
            ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
            return ns;
        }
    }

    public class ProperXmlNodeReader : XmlNodeReader
    {
        // Bug fix from this answer https://stackoverflow.com/a/30115691/3744182
        // To http://stackoverflow.com/questions/30102275/deserialize-object-property-with-stringreader-vs-xmlnodereader
        // By https://stackoverflow.com/users/8799/nathan-baulch
        public ProperXmlNodeReader(XmlNode node) : base(node) { }

        public override string LookupNamespace(string prefix)
        {
            return NameTable.Add(base.LookupNamespace(prefix));
        }
    }

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

        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()
	{
		Question42114531.V1.TestClass.Test();
	}
}
;