CSharp · Console
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.V3
{
// https://stackoverflow.com/questions/42114531/populating-any-elements-on-a-web-service-in-c-sharp
public class GenericRequestData_Type
{
private System.Xml.Linq.XElement[] anyField;
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.Linq.XElement[] Any
{
get
{
return this.anyField;
}
set
{
this.anyField = value;
}
}
}
class TestClass
{
internal static void Test()
{
// Taken from
// https://msdn.microsoft.com/en-us/library/mt693096.aspx
var contacts =
new XElement("Contacts",
new XElement("Contact",
new XElement("Name", "Patrick Hines"),
new XElement("Phone", "206-555-0144"),
new XElement("Address",
new XElement("Street1", "123 Main St"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
)
)
);
var genericRequest = new GenericRequestData_Type();
genericRequest.Any = new[] { contacts };
Console.WriteLine(genericRequest.GetXml());
}
}
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.V3.TestClass.Test();
}
}