Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XElement creation if the value is not Null

Tags:

c#

linq

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?

like image 875
user2067567 Avatar asked Dec 20 '22 06:12

user2067567


1 Answers

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"))
like image 189
Jon Skeet Avatar answered Jan 07 '23 16:01

Jon Skeet