using System.Collections.Generic;
using System.Xml.Serialization;
[XmlElement("PB")] public string PB { get; set; }
[XmlElement("MP")] public string MP { get; set; }
[XmlElement("Mode")] public string Mode { get; set; }
[XmlAttribute("PB")] public string PBAttribute { get => PB; set => PB = value; }
[XmlAttribute("MP")] public string MPAttribute { get => MP; set => MP = value; }
[XmlAttribute("Mode")] public string ModeAttribute { get => Mode; set => Mode = value; }
public bool ShouldSerializePB() => false;
public bool ShouldSerializeMP() => false;
public bool ShouldSerializeMode() => false;
public string Type { get; set; }
public Data Data { get; set; }
public PInstrument PInstrument { get; set; }
public static void Test()
foreach (var xml in GetXml())
Console.WriteLine("\nFor input XML:");
var response = xml.LoadFromXml<Response>();
var newXml = response.GetXml(omitStandardNamespaces: true);
Console.WriteLine("Re-serialized {0}:", response);
Console.WriteLine(newXml);
Assert.That(response.PInstrument.Data.PB == "blabla");
Assert.That(response.PInstrument.Data.MP == "blabla");
Assert.That(response.PInstrument.Data.Mode == "blabla");
static IEnumerable<string> GetXml() => new []
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<Data PB="blabla" MP="blabla" Mode="blabla" />
public static class XmlSerializationHelper
public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
using (var reader = new StringReader(xmlString))
return (T)(serial ?? 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();
using (var textWriter = new StringWriter())
var settings = new XmlWriterSettings() { Indent = true };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
(serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
public static void Main()
Console.WriteLine("Environment version: {0} ({1}, {2}, NewLine: {3}).",
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion,
System.Text.Json.JsonSerializer.Serialize(Environment.NewLine));
Console.WriteLine("Failed with unhandled exception: ");