I have xml code that would be something like this: file named: player.xml
<root>
<person>
<fname>Dwight</fname>
<lname>Howard</lname>
<vertLeap>
<try1>32.33</try1>
<try2>33.33</try2>
<try3>34.33</try3>
</vertLeap>
</person>
<person>
<fname></fname>
<lname>Jordan</lname>
<vertLeap>
<try1>40.33</try1>
</vertLeap>
</person>
</root>
This isn't my real xml, but should work for the example. Now I want to use linq to xml to read the data. Iam am trying like this.
Class:
public class Player
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Leap1 { get; set; }
public int Leap2 { get; set; }
public int Leap3 { get; set; }
public WritePlayertoDatabase()
{
//do stuff to write
}
}
Query:
XDocument xDoc = XDocument.Load("player.xml");
var player_query = from p xDoc.Desendants("person")
select new Player
{
FirstName = p.Element("fname"),
LastName = p.Element("lname"),
Leap1 = p.Element("try1"),
Leap2 = p.Element("try2"),
Leap3 = p.Element("try3")
};
I'm getting a NullReferenceException. Is there a way to test if the elements exist before I try to use the value? Or is there a way better way to accomplish this?