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?
So there are a few things wrong with your linq query.
1)
p.Element("fname")will return the fname XML Element, not a string. So you still need to get the element’s value. Similarly, the Leap1-3 properties are int, but you will get the element value as a stirng and need to convert it. But, try1-3 are not ints in the xml, so you probably want to change the type to somehting else in the Player class.2) try1 – tryx element s are all children of ‘vertleap’. You can’t directly get element ‘try1’ from ‘person’. It will be null.
So how about something more like this: