0

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())
                   ) )

1 Answer 1

2

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" />
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Anthony, this didn't solve my problem. Now with your code if : foos.Add(new Foo() {Bar = ""}); then the resulting XML is <Foo Bar="">. But I don't want <Foo Bar=""> to be shown in my resulting XML.
@BumbleBee, consider replaceing foo.Bar != null with !string.IsNullOrEmpty(foo.Bar) (and the same for foo.Baz).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.