using System.Collections.Generic;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Collections;
internal static readonly XmlSerializer xs;
XmlAttributes ignore = new XmlAttributes()
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Parent), "MyProperty", ignore);
overrides.Add(typeof(Child), "MyProperty", ignore);
xs = new XmlSerializer(typeof(Parent), overrides);
public static XmlSerializer Serializer
public SomeClass MyProperty { get; set; }
public List<Child> Children { get; set; }
public SomeClass MyProperty { get; set; }
public string Name { get; set; }
internal static void Test()
var xs = Parent.Serializer;
var test = new Parent { MyProperty = new SomeClass { Name = "I should not appear" }, Children = new List<Child> { new Child { MyProperty = new SomeClass { Name = "I should not appear" } } } };
var xml = test.GetXml(xs);
Assert.IsTrue(!xml.Contains("MyProperty"));
Console.WriteLine("\"MyProperty\" is not present in XML.");
public static void Main()
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();
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 class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
throw new AssertionFailedException("failed");