How to get attribute value using LINQ to XML?

后端 未结 2 1360
-上瘾入骨i
-上瘾入骨i 2021-02-05 14:52

  
    1
    Sam
    Male
    423         


        
2条回答
  •  无人及你
    2021-02-05 15:05

    This code will work even if there is any Phone elements exist for employee:

    var emplyees = 
        from emp in emplyeeDetails.Descendants("Employee").Take(10)
        let phones = emp.Descendants("Phone")
        orderby (int)emp.Element("EmpId")
        select new
        {
            Id = (int)emp.Element("EmpId"),
            Name = (string)emp.Element("Name"),
            Sex = (string)emp.Element("Sex"),
            WorkPhone = (string)phones.FirstOrDefault(p => (string)p.Attribute("Type") == "Work"),
            HomePhone = (string)phones.FirstOrDefault(p => (string)p.Attribute("Type") == "Home")                               
        };
    

    Use casting elements to string, int, etc instead of accessing Value property. Why? Because if there is some missing element or attribute in your xml, then you will get a NullReferenceException. But casting will return default value instead. So, code above will parse even xml like this:

    
      
        1
        Sam
        423-555-0124
        524-777-1234
      
    
    

提交回复
热议问题