I am using LINQ to convert from XML file to a class that I have created. no matter what I am trying I am getting 0 in the count of the list.
List<UpdateMember> updateMembers = new List<ExeTeam.UpdateMember>();
updateMembers = GetMember(doc);
try
{
IEnumerable<UpdateMember> member = from r in doc.Descendants("UpdateMember").Descendants("member")
select new UpdateMember()
{
Birthdate = (string)(r.Element("Birthdate")) == string.Empty ? DateTimeParser((DateTime)(r.Element("Birthdate"))) : DateTime.Now,
Email = (string)r.Element("Email") != null ? (string)r.Element("Email") : "",
FamilyStatus = (string)r.Element("Familystatus") != null ? (string)r.Element("Familystatus") : "",
ID = (int)r.Element("IdNumber") != 0 ? (int)r.Element("IdNumber") : 0,
Phone1 = (int)r.Element("Telephone1") != 0 ? (int)r.Element("Telephone1") : 0,
Phone2 = (int)r.Element("Telephone2") != 0 ? (int)r.Element("Telephone2") : 0,
phone3 = (int)r.Element("Telephone3") != 0 ? (int)r.Element("Telephone3") : 0
};
return member.ToList();
}
The xml
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<UpdateMember xmlns="http://tempuri.org/">
<member>
<Birthdate>25122012</Birthdate>
<Email>fake@testing.com</Email>
<Familystatus>single</Familystatus>
<IdNumber>12345678</IdNumber>
<Telephone1>123-4567890</Telephone1>
<Telephone2></Telephone2>
<Telephone3></Telephone3>
</member>
</UpdateMember>
In the line from r in doc.Decendants("")...
I have tried all kind of variations.
Thank to all
The problem is namespaces:
That means all your elements are in that namespace, by default. Your queries all try to look for elements which aren’t in a namespace, e.g.
This is very easy to fix in LINQ to XML:
Additionally, your attempt to handle missing data won’t work and is overly complicated. For example, this:
should be:
If you cast to
int, it won’t give a value of0if the value is missing – it will throw an exception. Casting toint?will give a null value instead.I would change your whole code to:
EDIT: As noted in comments, storing phone numbers as
intvalues is a really bad idea. You’d lose any formatting, you’d lose leading zeroes, and I’d expect many full phone numbers to be outside the range of anintanyway. I’d keep them as strings.