如何让使用LINQ to XML属性值? [英] how to get Attribute Value using linq to xml?
问题描述
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Sam</Name>
<Sex>Male</Sex>
<Phone Type="Home">423-555-0124</Phone>
<Phone Type="Work">424-555-0545</Phone>
</Employee>
</Employees>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
emplyeeDetails = XDocument.Load(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\LinqToXml\\Xmls\\" + "Employees.xml");
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.Element("Phone").Attribute("Type").Value,
HomePhone = emp.Element("Phone").Attribute("Type").Value,
};
DgrdEmployeeDetails.ItemsSource = emplyees.ToList();
}
使用上面的代码,我可以得到下面的结果。
Using above code i can get the result below.
不过,我需要的列(办公电话)值的 424-555-0545 代替的首页和列(家庭电话)值的 423-555-0124 代替的首页即可。 ?我应该为此做些什么
But i need the column(WorkPhone) value 424-555-0545 instead of Home and the column(HomePhone) value 423-555-0124 instead of Home. What should i do for that ?
推荐答案
使用其中,
方法:
对于首页的电话号码:
emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Home").Value
对于工作的电话号码:
emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Work").Value
-
emp.Elements(手机)
是一切电话元素的枚举的EMP
。 -
单
将得到满足指定属性的元素(如果有0或1个多元素满足的财产,将引发一个错误)。 -
phoneElement.Attribute(类型)。值
是属性类型(即家或工作) emp.Elements("Phone")
is a enumerable on all "Phone" elements ofemp
.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,
};
如果元素 EMP
可能没有工作的电话或首页的电话号码,上面的代码将提高在单
例外。为了应对这种情况下,必须更改您的代码:
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
将等于空
如果没有phone元素满足条件和字符串
浇铸在的XElement
等同于 XElement.Value
。
SingleOrDefault
will equal null
if no "Phone" element satisfy the condition and the string
cast on a XElement
is equivalent to XElement.Value
.
这篇关于如何让使用LINQ to XML属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!