2012-06-19 55 views
0

我有以下xml,我需要從同一個查詢中獲得2個值(請參閱*註釋): 這兩個值是關聯的,我可以獲得一組() or the other() but not using a single query.找到一個節點,它在一個查詢中匹配後代節點

Update I updated the xml below to include 2 nodes that exist under the node and added the namespace

Ideally I would like to get them both in a single query into a Dictionary

<root xmlns="http://www.blah.net/xsd/layout/2003-10-16"> 
    <header/> 
    <movement> 
     <movementHeader> 
      <desc>xyz</desc> 
     </movementHeader> 
     <detailHeader> 
      <desc>abc</desc> 
     </detailHeader> 
     <detail> 
      <!-- * need this value --> 
      <code>90125</code> 
      <subDetail> 
       <!-- * and need this value at same time --> 
       <amount>1200.00</amount> 
      </subDetail> 
     </detail> 
     <detail> 
      <!-- * need this value --> 
      <code>90126</code> 
      <subDetail> 
       <!-- * and need this value at same time --> 
       <amount>1300.00</amount> 
      </subDetail> 
     </detail> 
     <detail> 
      <!-- * need this value --> 
      <code>9012</code> 
      <subDetail> 
       <!-- * and need this value at same time --> 
       <amount>1400.00</amount> 
      </subDetail> 
     </detail> 
    </movement> 

回答

3

You can project to an anonymous type that holds the properties you want:

var results = xdoc.Descendants("detail") 
        .Select(x => new 
        { 
         Code = x.Element("code").Value, 
         Amount = x.Element("subDetail") 
           .Element("amount").Value 
        }); 

foreach (var item in results) 
{ 
    Console.WriteLine("Code = {0}, Amount = {1}", item.Code, item.Amount); 
} 

Tested and works, returns 3 results as expected.

To add this to a dictionary just add ToDictionary()

var dict = xdoc.Descendants("detail") 
       .Select(x => new 
       { 
        Code = x.Element("code").Value, 
        Amount = x.Element("subDetail") 
          .Element("amount").Value 
       }).ToDictionary(x => x.Code, x => x.Amount); 

編輯:

要考慮,你必須聲明和使用它的XML命名空間,更新下面的例子:

XNamespace ns = "http://www.blah.net/xsd/layout/2003-10-16"; 
var dict = xdoc.Descendants(ns + "detail") 
       .Select(x => new 
       { 
        Code = x.Element(ns + "code").Value, 
        Amount = x.Element(ns + "subDetail") 
          .Element(ns + "amount").Value 
       }).ToDictionary(x => x.Code, x => x.Amount); 
+0

嘗試了您的解決方案,結果沒有任何結果。 xml稍微複雜一點(上面已更新),因爲它具有添加到節點的奇怪節點,並且它有一個名稱空間。我懷疑NS是一個問題,並且將XNamespace添加到您的代碼示例中,但仍然不返回結果 – Tab

+1

@Tab:使用'Element((XNamespace)nsString +「tagname」)' – abatishchev

+0

我在發表評論之前嘗試了以下內容: XNamespace nsr = Settings.DefaultNamespace; ... 元素(nsr +「代碼」)。值, – Tab

0
var r = from d in doc.Root.Element("movement").Elements("detail") 
     let amount = (string)d.Element("subDetail").Element("amount") 
     select new 
     { 
      Code = (string)d.Element("code"), 
      Amount = Decimal.Parse(amount) 
     }; 
+0

此示例給出了一個NullReferenceException - 用於... – Tab

+0

@Tab:什麼行? – abatishchev

+0

由於您給出的整個樣本都作爲單個語句處理,因此很難區分哪個'行' – Tab

相關問題