Using XmlSerializer to create an element with attributes and a value but no sub-element

I find the answer here: Xmlserializer – Control Element-Attribute Pairing (revised). Here is how to do it: mark the value property with the [XmlText] attribute. public class Quantity { // your attributes [XmlAttribute] public string foo; [XmlAttribute] public string bar; // and the element value (without a child element) [XmlText] public int qty; }

ShouldSerialize*() vs *Specified Conditional Serialization Pattern

The intent of the {propertyName}Specified pattern is documented in XML Schema Binding Support: MinOccurs Attribute Binding Support. It was added to support an XSD schema element in which: The <element> element is involved. minOccurs is zero. The maxOccurs attribute dictates a single instance. The data type converts to a value type. In this case, xsd.exe … Read more

XmlSerializer List Item Element Name

Mark your class with the following attributes: [XmlType(“Account”)] [XmlRoot(“Account”)] The XmlType attribute will result in the output requested in the OP. Per the documentation: Controls the XML schema that is generated when the attribute target is serialized by the XmlSerializer

XmlSerializer won’t serialize IEnumerable

The way you serialize an IEnumerable property is with a surrogate property [XmlRoot] public class Entity { [XmlIgnore] public IEnumerable<Foo> Foo { get; set; } [XmlElement, Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public List<Foo> FooSurrogate { get { return Foo.ToList(); } set { Foo = value; } } } It’s ugly, but it gets the job done. The nicer … Read more

Deserialize XML To Object using Dynamic

You may want to try this. string xml = @”<Students> <Student ID=””100″”> <Name>Arul</Name> <Mark>90</Mark> </Student> <Student> <Name>Arul2</Name> <Mark>80</Mark> </Student> </Students>”; dynamic students = DynamicXml.Parse(xml); var id = students.Student[0].ID; var name1 = students.Student[1].Name; foreach(var std in students.Student) { Console.WriteLine(std.Mark); } public class DynamicXml : DynamicObject { XElement _root; private DynamicXml(XElement root) { _root = root; } … Read more

Memory Leak using StreamReader and XmlSerializer

The leak is here: new XmlSerializer(typeof(XMLObj), new XmlRootAttribute(“rootNode”)) XmlSerializer uses assembly generation, and assemblies cannot be collected. It does some automatic cache/reuse for the simplest constructor scenarios (new XmlSerializer(Type), etc), but not for this scenario. Consequently, you should cache it manually: static readonly XmlSerializer mySerializer = new XmlSerializer(typeof(XMLObj), new XmlRootAttribute(“rootNode”)) and use the cached serializer … Read more

tech