将xdocument的linq查询附加到列表

时间:2012-03-21 14:24:52

标签: c# xml linq linq-to-xml

在我的代码的一个方面苦苦挣扎,我希望有人可以解释一下。

我在一个简单的foreach循环中多次提取xml文档。我想将我的linq查询附加到列表中,但每次都会重写列表。这是代码:

IEnumerable<TranList> tList;
foreach (var t in otherList)
{
         //pulling xml data from service here - code not shown
         XDocument xDoc = XDocument.Parse(xmlFromService);
         tList = from x in xDoc.Descendants("Items")
         select new TranList
         {
             BusDate = x.Descendants("BusDate").First().Value,
             SeqNum = x.Descendants("SeqNum").First().Value,
             Amount = x.Descendants("Amount").First().Value,
             Credit = x.Descendants("Credit").First().Value
         };
}

这是我的xml供参考:

<Items>
    <DbAmount>25,465.58</DbAmount>
    <DBCount>296</DBCount>
    <CrAmount>.00</CrAmount>
    <CrCount>0</CrCount>
    <Item>
        <ID>0</ID>
        <BusDate>20090126</BusDate>
        <BlockNum>729</BlockNum>
        <SeqNum>2</SeqNum>
        <RelSeqNum>0</RelSeqNum>
        <Serial />
        <Routing>211690953</Routing>
        <Account>123456789</Account>
        <Amount>30.00</Amount>
        <Currency>USD</Currency>
        <Credit>DEBIT</Credit>
        <Onus>TRANSIT</Onus>
    </Item>
    <Item>
    . . . . . . . . . . . . . . .
    </Item>
    . . . . . . . . . . . . . . .
</Items>

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

将其更改为:

List<TranList> tList = new List<TranList>();

foreach (var t in otherList)
{
     //pulling xml data from service here - code not shown
     XDocument xDoc = XDocument.Parse(xmlFromService);
     tList.AddRange(from x in xDoc.Descendants("Items")
     select new TranList
     {
         BusDate = x.Descendants("BusDate").First().Value,
         SeqNum = x.Descendants("SeqNum").First().Value,
         Amount = x.Descendants("Amount").First().Value,
         Credit = x.Descendants("Credit").First().Value
     });
}

重要的是,tList现在是List<TranList>,您可以通过AddRange(...)向其添加查询结果。

答案 1 :(得分:0)

您目前每次都重新分配tList,而不是连接:

tList = (from x in xDoc.Descendants("Items")
        select new TranList
        {
            BusDate = x.Descendants("BusDate").First().Value,
            SeqNum = x.Descendants("SeqNum").First().Value,
            Amount = x.Descendants("Amount").First().Value,
            Credit = x.Descendants("Credit").First().Value
        }).Concat(tList);

但为什么你首先需要foreach?你现在甚至没有使用循环变量,所以这没有多大意义。

答案 2 :(得分:0)

试试这个:

var result = from t in otherList
             from x in XDocument.Parse(xmlFromService(t)).Root.Elements("Item")
             select new TranList
             {
                 BusDate = (string)x.Element("BusDate"),
                 SeqNum = (string)x.Element("SeqNum"),
                 Amount = (string)x.Element("Amount"),
                 Credit = (string)x.Element("Credit")
             };