2010-04-22 60 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); 
     }