1. class object
[Serializable, XmlRoot("Field")] public class Field { [XmlAttribute("nm")] public string Name { get; set; } [XmlText] public string Text { get; set; } }2. serialize
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true })) { new XmlSerializer(typeof(Field)).Serialize(writer, type, ns); } string xmlString = sb.ToString();3. deserialize
XmlReader reader = XmlTextReader.Create(new StringReader(xmlString)); XmlSerializer xmlSerializer = new XmlSerializer(typeof(Field)); var result = (Field)xmlSerializer.Deserialize(reader); reader.Close();
4. Sample
public static XDocument Serialize<T>(this T source)
{
var ser = new XmlSerializer(source.GetType());
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
ser.Serialize(writer, source);
}
return XDocument.Parse(sb.ToString());
}
public static T Deserialize<T>(this XDocument xmlDocument)
{
var xmlSerializer = new XmlSerializer(typeof(T));
using (var reader = xmlDocument.CreateReader())
return (T)xmlSerializer.Deserialize(reader);
}