Friday, October 11, 2019

XML Serialization: How to serialize a property as XML attribute in serialization

.NET framework provides a set of attributes class (for example, XMLElement, XMLAttribute etcs) which controls the XML serialization from .net object to XML.
 XMLAttribute is used to include a property of object as attribute in XML and you can also provide own the attribute name, which is different from property name.

Here is an example in C# to serialize a property as XML attribute.

   public class Order
    {
        public int OrderNumber { get; set; }
        public string Item { get; set; }
        public string User { get; set; }

        [XmlAttribute(AttributeName="OrderVersion")]
        public string version { get; set; }
    }

In above Order Class, version property is being decorated with XMLAttribute, this field will be serialized as XMLAttrbute “OrderVersion” of parent XML Element “Order”

Order order = new Order { Item = "Iphone 7",  OrderNumber = 12, User = "Smith", version = "1.00" };

Here is serialized XML string corresponding from  above Order instance


XML Serialization - XMLAttribute


Other related posts:

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...