using System.Collections.Generic;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Globalization;
using System.ComponentModel.DataAnnotations;
using System.Collections;
[XmlRoot(ElementName = "author")]
public XmlElement NameElement { get; set; }
return NameElement == null ? null : NameElement.InnerXml;
var element = new XmlDocument().CreateElement("name");
element.InnerXml = value;
[XmlRoot(ElementName = "book")]
[XmlElement(ElementName = "author")]
public Author Author { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlRoot(ElementName = "books")]
[XmlElement(ElementName = "book")]
public List<Book> Book { get; set; }
<name>Author-1<ref>1</ref></name>
<name>Author-1<ref>1</ref></name>
internal static void Test()
var books = xml.LoadFromXML<Books>();
var names = books.Book.Select(b => b.Author.Name).ToArray();
Console.WriteLine("Deserialized name strings: ");
Console.WriteLine(String.Join("\n", names));
var reserializedXML = books.GetXml(true);
Console.WriteLine("Re-serialized XML: ");
Console.WriteLine(reserializedXML);
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, 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))
new XmlSerializer(obj.GetType()).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();