How to get attribute value using LINQ to XML?

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

  
    1
    Sam
    Male
    423         


        
2条回答
  •  误落风尘
    2021-02-05 15:05

    Use the Where method:

    For the Home phone number:

    emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Home").Value
    

    For the Work phone number:

    emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Work").Value
    
    • emp.Elements("Phone") is a enumerable on all "Phone" elements of emp.
    • Single will get the element that satisfy the specified property (if there are 0 or more than 1 element that satisfy the property, an error is raised).
    • phoneElement.Attribute("Type").Value is the value of the attribute "Type" (ie "Home" or "Work")

    Then, your code should be:

    var emplyees = from emp in emplyeeDetails.Descendants("Employee").Take(10)
                    orderby emp.Element("EmpId").Value ascending
                    select new
                    {
                        Id = emp.Element("EmpId").Value,
                        Name = emp.Element("Name").Value,
                        Sex = emp.Element("Sex").Value,
                        WorkPhone = emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Home").Value,
                        HomePhone = emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Work").Value,
                    };
    

    If the element emp may have no Work phone or Home phone number, the above code will raise an exception in the Single. To deal with this case you have to change your code to:

    (string)emp.Elements("Phone").SingleOrDefault(phoneElement => phoneElement.Attribute("Type").Value == "Home")
    

    SingleOrDefault will equal null if no "Phone" element satisfy the condition and the string cast on a XElement is equivalent to XElement.Value.

提交回复
热议问题