Reputation: 891
I am playing around with some LINQ to XML and I have been unable to get my query working the way I want it to. I am able to get a single element working like firstName, but when I add another I see red underlines in VS telling me an object reference is missing. I am assuming this is a syntax issue. I am fairly new to LINQ so sorry for the dumb question. I have been unable to find an example that covers my scenario. Any guidance would be appreciated.
Member MyMember = new Member();
MyMember.fName = "Willy";
MyMember.lName = "Wonka";
MyMember.Address1 = "333 Chocolate Avenue";
MyMember.City = "Candytown";
MyMember.State = "North Carolina";
MyMember.Zip = "05684";
List<Member> mlist = new List<Member>();
mlist.Add(MyMember);
XElement customersElement = new XElement("primaryNames",
from Member in mlist
select new XElement("firstName", Member.fName),
new XElement("last", Member.lName),
new XElement("address", Member.Address1),
new XElement("city", Member.City),
new XElement("state", Member.State),
new XElement("zip", Member.Zip));
Upvotes: 1
Views: 56
Reputation: 12821
As you are trying to iterate a list, each element in the list is a child element of primaryNames
. So create another child element primaryName
as said below.
XElement customersElement = new XElement("primaryNames",
from mem in mlist
select new XElement("primaryName",
new XElement("firstName", mem.fname),
new XElement("last", mem.lname),
new XElement("city", mem.city),
new XElement("state", mem.state)
));
Upvotes: 1