XML查询仅返回第一个元素

时间:2015-10-17 03:41:49

标签: c# linq linq-to-xml

我需要返回此XML中的3个scancode项元素,而不是返回第一个元素3次。我对LINQ 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);
        }

1 个答案:

答案 0 :(得分:0)

这将为您提供预期的输出: -

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

您已拥有order引用变量,该变量包含Item集合。无需更进一步,您可以使用order本身。

根据您当前的代码,您尝试在item集合中找到元素Transaction,以便找到第一个元素。