Add attributes to XML element based on the input
How can I check whether the value for an attribute is not null, inside the LINQ query. If it is not null then add the attribute to the XML element?
for ex : First = AAA, Last = BBB, Suffix = Jr. Then my XML should look like (As I didn't pass any value for Prefix and type they should not appear in the XML)
<Subject>
</Name First= "AAA" Last ="BBB" Suffix="Jr">
</Subject>
Thanks BB
from i in DriverNames
select new XElement(Subject,
new XElement(Name,
new XAttribute("type", i.nameType),
new XAttribute(First, i.First.ToString().Trim().ToUpper()),
new XAttribute(last, i.Last.ToString().Trim().ToUpper()),
new XAttribute(Prefix, i.Prefix.ToString().Trim().ToUpper()),
new XAttribute(Suffix, i.Suffix.ToString().Trim()开发者_运维百科.ToUpper())
) )
You can simply check for null. XElement
accepts a params array of items, and nulls are acceptable and will basically get discarded. So check your values against null and move on. An example:
class Foo
{
public string Bar { get; set; }
public string Baz { get; set; }
}
...
List<Foo> foos = new List<Foo>();
foos.Add(new Foo() { Bar = "Dog" });
foos.Add(new Foo() { Baz = "Cat" });
var query = from foo in foos
select new XElement("Foo",
!string.IsNullOrEmpty(foo.Bar) ? new XAttribute("Bar", foo.Bar) : null,
!string.IsNullOrEmpty(foo.Bar) ? new XAttribute("Baz", foo.Baz) : null);
And the resulting XML, you'll see it renders each element as you would desire.
<Foo Bar="Dog" />
<Foo Baz="Cat" />
精彩评论