When you create an object with a bool field, that field is initialized and defaulted to the value of false. Under normal conditions, this value will get serialized every time. However, what if we only care about capturing that value when the value is true? It turns out that we can use DefaultValueAttribute. The first thing that may stand out to you is that this attribute lives in the System.ComponentModel namespace, and not in an XML namespace. The online help also mentions that this is used for visual designers and code generators. XmlSerializer also uses this attribute to decide whether or not to stream the value during serialization, since it's really a form of a code generator (more on that in a later post). If the value of the field or property matches the value that you specify in the DefaultValueAttribute, then that property will not be streamed.
Using an XmlAttributeAttribute, you can specify that a certain property will be expressed as an XML attribute instead of an XML element. To demonstrate both of these concepts, see the following code:
public class Url{ [XmlAttribute("address")] public string Address; [XmlAttribute("primary"), DefaultValue(false)] public bool Primary; public Url() { }} static void Main(string[] args){ Url u = new Url(); u.Address = "http://testing/"; string xml = GetXMLFromObject(u); Console.WriteLine(xml);}
public class Url
{
[XmlAttribute("address")]
public string Address;
[XmlAttribute("primary"), DefaultValue(false)]
public bool Primary;
public Url()
}
static void Main(string[] args)
Url u = new Url();
u.Address = "http://testing/";
string xml = GetXMLFromObject(u);
Console.WriteLine(xml);
This produces roughly the following output (XML namespace information is stripped here. I will show how to do this in code with a future post). Notice that the Primary attribute is not generated because it matches the DefaultValue.<?xml version="1.0" encoding="utf-16"?><Url address="http://testing/" />
<?xml version="1.0" encoding="utf-16"?><Url address="http://testing/" />
<?xml version="1.0" encoding="utf-16"?>
<Url address="http://testing/" />
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.