2012-05-10 39 views
0

可能重複:
Use LINQ to read all nodes from XML使用LINQ C#中的XML所有節點

我想讀在C#中的Windows應用程序使用LINQ的XML文件。下面給出了xml字符串的示例。

<Root> 
<Name>John Doe</Name> 
<Data>FBCCF14D504B7B2DBCB5A5BDA75BD93B</Data> 
<customer>true</customer> 
<Accounts>1</Accounts> 
<dataSet> 
    <Type1>Found matching records.</Type1> 
    <Type2>No matches found.</Type2> 
    <Type3>Found matching records.</Type3> 
</dataSet> 
</Root> 

我想要顯示的<dataset>標籤和<datatag>我想讀<customer>標籤以及裏面的所有數據。

我創建了一個包含成員的類(字符串類型,字符串狀態)。在哪裏類型我想存儲類型1,2 ...和在狀態我想存儲什麼是在類型節點。

我能做到這一點,但在代碼中,我不得不放棄

type1 = (string)row.Element("type1"), type2=(string)row.Element("type2"), 我想在這我沒有提到每一個類型的通用代碼。換句話說,我想讀標籤名稱而不讀標籤的所有子節點。我花了2個小時在谷歌搜索這個,但還沒有發現任何東西。

預期輸出

節省類對象(類型和狀態)的信息。

,我想讀的客戶標籤,這樣我可以知道這個人是否已經是客戶

任何幫助將是非常讚賞。

感謝

更新

根據輸入從拉斐爾奧爾索斯收到

我有以下代碼:

var list = xml.Descendants("dataSet").Elements() 
      .Select(m => new CustomerInfo 
          { 
           Type = m.Name.LocalName, 
           Value = m.Value 
          }).ToList(); 


     foreach (CustomerInfo item in list) 
     { 
      MessageBox.Show(item.Type+ " "+item.Value); 

     } 

和用於讀取客戶標籤我已經寫了碼。

var isCustomer = from customer in xmlDoc.Descendants("Root") 
      select new 
      { 
       customer = tutorial.Element("customer").Value, 
      } 

我可以在一個查詢嗎?或者這種方法在性能上並不那麼沉重,所以我可以使用它?

+0

我在這裏找到部分答案http://stackoverflow.com/questions/5978926/c-using-linq-to-get-a-ienumerable-collection-of-xml-nodes-to-traverse – ace120387

回答

1

這樣的事情?

var q = xml.Descendants("dataSet").Elements() 
      .Select(m => new 
          { 
           type = m.Name.LocalName, 
           value = m.Value 
          }).ToList(); 

您也可以直接填入你的「類成員」列表

var list = xml.Descendants("dataSet").Elements() 
       .Select(m => new <TheNameOfYourClass> 
           { 
            Type = m.Name.LocalName, 
            Value = m.Value 
           }).ToList(); 

編輯:

獲得「客戶」的價值,我會做另一個查詢

var customerElement = xml.Element("customer"); 
var isCustomer = customerElement != null && customerElement.Value == "true"; 

所以你可以混合所有它在一個小函數

public IList<YourClass> ParseCustomers(string xmlPath, out isCustomer) { 
    var xml = XElement.Load(xmlPath); 
    var customerElement = xml.Element("customer"); 
    isCustomer = customerElement != null && customerElement.Value == "true"; 
    return xml.Descendants("dataSet").Elements() 
        .Select(m => new <YourClass> 
            { 
             Type = m.Name.LocalName, 
             Value = m.Value 
            }).ToList(); 
} 
+0

謝謝,它正在工作,但它只會返回數據集下的元素。我也想標籤。有一種方法可以一次完成嗎?當我替換xml.Descendants(「數據集」)xml.Descendants(「根」)> 我得到的類型=數據集和值=所有值下標籤 – ace120387

+0

不清楚你的第一個問題:請你給一個列表基於你的xml例子的預期結果? –

+0

預期結果: 類型和已完成的值。 我想閱讀標籤。所以我可以知道這個人是否已經是客戶。 – ace120387