获取节点属性xml C#

时间:2014-12-15 08:06:25

标签: c# xml linq foreach xml-parsing

我试图从xml文件中获取所有节点,但我无法获得具有Home和Work等属性的节点。好吧,在我的情况下,我可以打电话回家而不是电话工作。谢谢。

这是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>
      <Address>
          <Street>7A Cox Street</Street>
          <City>Acampo</City>
          <State>CA</State>
          <Zip>95220</Zip>
          <Country>USA</Country>
      </Address>
    </Employee>
</Employee>  

这是我在C#中的代码:

XElement xelement = XElement.Load("employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
Console.WriteLine("List of all Employee Names along with their ID:");
foreach (var employee in employees)
{     
   employee.Element("EmpId").Value);
   Console.WriteLine("SEX: {0}", employee.Element("Sex").Value);
   Console.WriteLine("Home: {0}", employee.Element("Phone").Value);
   Console.WriteLine("Work: {0}\n", employee.Element("Phone").Value);
}

结果:

enter image description here

祝:

enter image description here

3 个答案:

答案 0 :(得分:2)

您需要使用Attribute方法来获取属性。您需要使用Phone属性Type查询Home元素。例如:

Console.WriteLine("Home: {0}",
    employee.Elements("Phone")
            .Single(x => x.Attribute("Type").Value == "Home")
            .Value);

如果不是您想要的类型的电话号码,或者有多个电话号码,您应该考虑一下您想要做什么。 (Single方法只需要一个匹配。还有FirstLast,以及FirstOrDefaultLastOrDefault,它们将返回{ {1}}如果没有匹配项。)

答案 1 :(得分:1)

这应该是第一个名为Phone的元素,其中属性名称为'Home'

employee.Elements("Phone")
                  .First(x => x.Attribute("name").Value == "Home");

答案 2 :(得分:1)

这是您的完整代码

static void Main(string[] args)
{
   XElement xelement = XElement.Load("Employees.xml");
   IEnumerable<XElement> employees = xelement.Elements();
   Console.WriteLine("List of all Employee Names along with their ID:");
   foreach (var employee in employees)
   {     
      Console.WriteLine("EmpId: {0}", employee.Element("EmpId").Value);
      Console.WriteLine("SEX: {0}", employee.Element("Sex").Value);
     //Console.WriteLine("Home: {0}", employee.Element("Phone").Value);
      Console.WriteLine("Home: {0}", employee.Elements("Phone")
               .Single(x => x.Attribute("Type").Value == "Home").Value);
      Console.WriteLine("Home: {0}", employee.Elements("Phone")
               .Single(x => x.Attribute("Type").Value == "Work").Value);
     //Console.WriteLine("Work: {0}\n", employee.Element("Phone").Value);
   }
   Console.Read();
}