2015-10-17 69 views
0

我需要返回此XML中的3個scancode項目元素,而不是返回第一個元素3次。我對LINQ XML沒有太多的瞭解。我瀏覽過網站上的其他帖子,這裏有一點不同。XML查詢僅返回第一個元素

### Expected Output ### 
10/14/2015 
05:00 
044000031910 
044000031912 
044000031913 

10/15/2015 
06:00 
044000031920 
044000031922 
044000031923 

### Current Output ### 
10/14/2015 
05:00 
044000031910 
044000031910 
044000031910 

10/15/2015 
06:00 
044000031920 
044000031920 
044000031920 

XML實例

<Orders> 
<Transaction> 
    <TransDate>10/14/2015</TransDate> 
    <TransTime>05:00</TransTime> 
    <Item> 
     <SequenceNumber>1</SequenceNumber> 
     <ScanCode>044000031910</ScanCode> 
    </Item> 
    <Item> 
     <SequenceNumber>2</SequenceNumber> 
     <ScanCode>858310004011</ScanCode> 
    </Item> 
    <Item> 
     <SequenceNumber>3</SequenceNumber> 
     <ScanCode>092657011712</ScanCode> 
    </Item> 
</Transaction> 

<Transaction> 
    <TransDate>10/15/2015</TransDate> 
    <TransTime>06:00</TransTime> 
    <Item> 
     <SequenceNumber>1</SequenceNumber> 
     <ScanCode>044000031920</ScanCode> 
    </Item> 
    <Item> 
     <SequenceNumber>2</SequenceNumber> 
     <ScanCode>858310004021</ScanCode> 
    </Item> 
    <Item> 
     <SequenceNumber>3</SequenceNumber> 
     <ScanCode>092657011722</ScanCode> 
    </Item> 
</Transaction> 

C#示例

var doc = XDocument.Load("Data.xml"); 
     var data = from item in doc.Descendants("Transaction") 
        select new 
        { 
         TransDate = (string)item.Element("TransDate"), 
         TransTime = (string)item.Element("TransTime"), 
         items = from order in item.Elements("Item") 
           select new 
           { 
            ScanCode = (string)item.Element("Item").Element("ScanCode") 
           } 

        }; 
     foreach (var Item in data) 
     { 
      textBox1.AppendText(Item.TransDate + Environment.NewLine); 
      textBox1.AppendText(Item.TransTime + Environment.NewLine); 
      foreach (var item in Item.items) 
      { 
       textBox1.AppendText(item.ScanCode + Environment.NewLine); 
      } 
      textBox1.AppendText(Environment.NewLine); 
     } 

回答

0

這會給你所期望的輸出: -

select new 
    { 
     ScanCode = (string)order.Element("ScanCode") 
    } 

您已有order參考變量,其中包含Item集合。沒有必要走得更遠,您可以使用order本身。

根據您當前的代碼,您正試圖在Transaction集合中找到元素item,因此它只能找到第一個。

+1

工作完美!非常感謝! – DjKornNut