2010-04-22 69 views
0

以下是我的XML文件。基于<type>,我需要获得所有节点值<customers></customers>使用LINQ搜索XML

<?xml version='1.0' encoding='utf-8' ?> 
<All> 
    <Customers> 
     <Customer> 
      <Name> Brisbane </Name> 
      <age> 18 </age> 
      <id> 1234 </id> 
      <type> owner </type> 
     </Customer> 

     <details> 
      <address> 123,Brisbane </address> 
      <location> Indonesia </location> 
     </details> 
     <contact> 
      <phone> 123456789 </phone> 
      <fax> 12548976 </fax> 
     </contact> 
    </Customers> 

    <Customers> 
     <Customer> 
      <Name> Manila</Name> 
      <age> 16 </age> 
      <id> 1200 </id> 
      <type> seller</type> 
     </Customer> 

     <details> 
      <address> Rich Street </address> 
      <location> Fabia </location> 
     </details> 

     <contact> 
      <phone> 987456321</phone> 
      <fax> 23654897 </fax> 
     </contact> 
    </Customers> 
</All> 

例如,在上面的例子中,有两种类型:

  1. 所有者
  2. 卖方。

所以,如果我选择“所有者”我需要的细节,所以如下

Brisbane 
18 
1234 
123,Brisbane 
Indonesia 
123456789 
12548976 

如果我选择“卖方”我需要了解详细内容如下。

Manila 
16 
1200 
Rich Street 
Fabia 
987456321 
23654897 

那么我该怎么做?什么样的代码呢?

+0

你确定你的xml文件是它应该是? -tag不应包含所有客户,而不是每个标签一个孩子? – 2010-04-22 12:26:02

+1

欢迎来到StackOverflow!在这个网站上,如果你展示了一些你已经试过并且无法弄清楚的代码,你将更有可能得到答案。通用的“请给我代码”通常不会让你走得很远。 – CoderDennis 2010-04-26 15:31:46

回答

0

OK说XML称为“文档”。

 var results_sellers = (from item in doc.Descendants("Customer") 
           where (string)item.Element("type") == "seller" 
           select new { 
            Name = item.Element("Name").Value, 
            Age = item.Element("Age").Value, 
            Id = item.Element("Id").Value, 
            Type = item.Element("type").Value 
           }); 

     //Then you can do the following 
     foreach (var e in results_sellers) 
     { 
      Console.WriteLine(e.Name, e.Id, e.Type, e.Age); 
     }