CSharp · Console
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Text.Json;
using NUnit.Framework; //NUnit.Framework.AssertionException
#nullable enable
//https://stackoverflow.com/questions/76950645/c-sharp-deserialize-known-unknownelement-from-xml
public class TestClass
{
public static void Test()
{
var s = "I'm from Foo.A";
Console.WriteLine(s.GetXml(omitStandardNamespaces : true));
}
}
public static partial class XmlExtensions
{
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() ?? typeof(T))).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
}
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: {0} ({1}, {2})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}