如何从属性中获取值

本文关键字:获取 从属性 | 更新日期: 2023-09-27 18:16:50

我有一个简单的XML文件结构,像这样:

  <Employee>
    <EmpId>1</EmpId>
    <Name>Sam</Name>
    <Sex>Male</Sex>
    <Phone Type="Home">423-555-0124</Phone>
    <Phone Type="Work">424-555-0545</Phone>
    <Address>
      <Street>7A Cox Street</Street>
      <City>Acampo</City>
      <State>CA</State>
      <Zip>95220</Zip>
      <Country>USA</Country>
    </Address>
  </Employee>

和更多的Employees在XML文件

我只想选择两个值:NamePhone,属性为Type = Home

var query = from nm in xElement.Elements("Employee")
            orderby nm.Element("EmpId") descending
            select new 
            {
              Name = nm.Element("Name").Value,
              work_phone = ((string)nm.Element("Phone").Attribute("Type") == "Home").ToString().Single()
        };

但它不起作用。问题是在work_phone (IComparable例外)。我如何得到这个值?

如何从属性中获取值

您可以这样尝试:

work_phone = (string)nm.Elements("Phone")
                       .FirstOrDefault(o => (string)o.Attribute("Type") == "Home");

另一个问题是在orderby子句。尝试将<EmpId>的值转换为int,使其具有可比性:

.....
orderby (int)nm.Element("EmpId") descending
.....

这是两个被选中的值:

var query = from nm in xElement.Elements("Employee")
                        orderby nm.Element("EmpId") descending
                        select new
                        {
                            Name = nm.Element("Name").Value,
                            HomePhone = (string)nm.Elements("Phone").SingleOrDefault(y => (string)y.Attribute("Type") == "Home")
                        };
var query = from nm in xElement.Elements("Employee")
            orderby (int)nm.Element("EmpId") descending
            select new
            {
                Name = nm.Element("Name").Value,
                work_phone = nm.Elements("Phone").First(p=>p.Attribute("Type").Value=="Home").Value
            };

文档如下:- http://www.dotnetcurry.com/showarticle.aspx?ID=564

XElement xelement = XElement.Load("..''..''Employees.xml");
var homePhone = from phoneno in xelement.Elements("Employee")
                where (string)phoneno.Element("Phone").Attribute("Type") == "Home"
                select phoneno;
Console.WriteLine("List HomePhone Nos.");
foreach (XElement xEle in homePhone)
{
    Console.WriteLine(xEle.Element("Phone").Value);
}

开始:

var xml_data = "<Employee> <EmpId>1</EmpId> <Name>Sam</Name> <Sex>Male</Sex> <Phone Type='"Home'">423-555-0124</Phone> <Phone Type='"Work'">424-555-0545</Phone> <Address> <Street>7A Cox Street</Street> <City>Acampo</City> <State>CA</State> <Zip>95220</Zip> <Country>USA</Country> </Address> </Employee>";
            var xdoc = XDocument.Parse(xml_data);
            var result = xdoc.Elements("Employee").
                Where((x) =>
                    {
                        var home_phones = x.Elements("Phone").Where(y => (string)y.Attribute("Type") == "Home").ToList();
                        return home_phones.Count > 0;
                    }).
                ToList();