I am trying to create XML from a List. I am creating a Anonymous class from the list to form XML:
var xEle = new XElement("Employees",
from emp in empList
select new XElement("Employee",
new XElement("ID", emp.ID),
new XElement("FName", emp.FName),
new XElement("LName", emp.LName)
));
How do I handle if Fname
or Lname
is null?
Also I want to Add elements dynamically only if the object is not null. For example if Fname
is null, I need to skip creating Fname:
new XElement("ID", emp.ID),
new XElement("LName", emp.LName)
How do I do that?
Your code doesn't actually show an anonymous type at all - just XElement
creation. However, you can use the fact that LINQ to XML will ignore null
values when adding content. So you can use:
select new XElement("Employee",
new XElement("ID", emp.ID),
emp.FName == null ? null : new XElement("FName", emp.FName),
emp.LName == null ? null : new XElement("LName", emp.LName)
)
Or you could write an extension method on string
:
public static XElement ToXElement(this string content, XName name)
{
return content == null ? null : new XElement(name, content);
}
And call it with:
select new XElement("Employee",
emp.ID.ToXElement("ID"),
emp.FName.ToXElement("FName"),
emp.LName.ToXElement("LName"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With