Skip to main content
 首页 » 编程设计

c#之LINQ to XML 查询中的 NullReferenceException

2024年02月20日10kuangbin

<分区>

我有这样的 xml 代码: 文件名为: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> 

这不是我真正的 xml,但应该适用于示例。 现在我想使用 linq to xml 来读取数据。我正在尝试这样。

类:

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 
    } 
} 

查询:

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") 
                   }; 

我收到 NullReferenceException。有没有办法在我尝试使用该值之前测试元素是否存在?还是有更好的方法来实现这一目标?