Linq 2 XML不返回基于属性值的元素

时间:2016-03-02 18:45:32

标签: c# xml linq linq-to-xml

我有以下XML ...

<?xml version="1.0" encoding="utf-8"?>
<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>
    <Address>
      <Street>7A Cox Street</Street>
      <City>Acampo</City>
      <State>CA</State>
      <Zip>95220</Zip>
      <Country>USA</Country>
    </Address>
    <Employee>
      <EmpId>5</EmpId>
      <Name>Kenneth Lowrey</Name>
      <Sex>Male</Sex>
      <Phone Type="Home">555-555-3477</Phone>
      <Phone Type="Work">444-123-2557</Phone>
      <Address>
        <Street>6026 Amberwoods Drive</Street>
        <City>Boca Raton</City>
        <State>FL</State>
        <Zip>33433</Zip>
        <Country>USA</Country>
      </Address>
    </Employee>
  </Employee>
</Employees>

我有以下控制台应用程序代码......

using System;
using System.Xml.Linq;
using System.Linq;

class Program
{
    public static void Main(String[] args)
    {
        String strPath = @"C:\XMLExample\Employees.xml";
        XElement xEle = XElement.Load(strPath);

        var empquery = from e in xEle.Descendants("Employee")
                       select new
                           {
                               name = e.Element("Name").Value,
                               homephone = (string)e.Element("Phone").Attribute("Type").Value=="Home" ? e.Element("Phone").Value : "",
                               workphone = (string)e.Element("Phone").Attribute("Type").Value=="Work" ? e.Element("Phone").Value : "",
                           };

        foreach (var e in empquery)
        {
            Console.WriteLine("{0}'s home phone is {1} work phone is {2}", e.name, e.homephone, e.workphone);
        }

        Console.WriteLine("Press <enter> to continue");
        Console.ReadLine();
    }
}

我正在尝试将查询表达式中的家庭和工作电话号码分开。

但是我只能获得家庭电话号码。

enter image description here

我做错了什么?

0 个答案:

没有答案