I am generating XML documents documents using LINQ to XML. I want the XML document to be minimal, i.e. seldom used properties should be omitted. Currently, I am doing it like this:
XElement element = new XElement("myelement",
new XAttribute("property1", value1),
new XAttribute("property2", value2));
if (!string.IsNullOrEmpty(rareValue1))
{
element.Add(new XAttribute("rareProperty1", rareValue1));
}
if (!string.IsNullOrEmpty(rareValue2))
{
element.Add(new XAttribute("rareProperty2", rareValue2));
}
if (!string.IsNullOrEmpty(rareValue3))
{
element.Add(new XAttribute("rareProperty3", rareValue3));
}
But actually, if would like to omit the “if”-statements, because they are not very elegant and they contradict the LINQ to XML philosophy where you can easily create XML trees by nesting as described in Creating Trees in XML.
So, I would like to do something like this:
XElement element = new XElement("myelement",
new XAttribute("property1", value1),
new XAttribute("property2", value2),
new XAttribute("rareProperty1", string.IsNullOrEmpty(rareValue1) ? Flag.Omit : rareValue1),
new XAttribute("rareProperty2", string.IsNullOrEmpty(rareValue2) ? Flag.Omit : rareValue1),
new XAttribute("rareProperty3", string.IsNullOrEmpty(rareValue3) ? Flag.Omit : rareValue1),
);
I.e. the C# source code contains all child attributes of myelement inside its constructor. And Flag.Omit would be some way to instruct LINQ-to-XML not to generate an XML attribute.
Is this possible with standard LINQ to XML or with some generic utility function?
The various ways of adding child nodes all ignore
nullvalues – so all you need is a helper method:Then: