1

我有以下xml。

<?xml version="1.0" encoding="utf-8" ?>
<MESSAGE ID="PND">
    <STORE ID="6697">
        <HEADER ID ="1" 
                LOADCLOSEDDATETIME="20130312121212" 
                DELIVERYDATE="20130312" 
                TRAILERID="" 
                TRIPROUTEID="" 
                DEPOTCODE=""/>
        <RECORD TPNB="123456666" 
                NOOFCASES="" 
                OUTERCASELENGTH="1" 
                OUTERCASEWIDTH="2" 
                OUTERCASEHEIGHT="3" 
                UNITSPERCASE="" 
                USEBYDATE="20130312121212" 
                MU="">
        </RECORD >
        <RECORD TPNB="123456666" 
                NOOFCASES="" 
                OUTERCASELENGTH ="1" 
                OUTERCASEWIDTH="2" 
                OUTERCASEHEIGHT="3" 
                UNITSPERCASE=""  
                USEBYDATE="20130312121212" 
                MU="">
        </RECORD>
    </STORE>
    <STORE ID="6647">
        <HEADER ID ="1" 
                LOADCLOSEDDATETIME="20130312121212"
                DELIVERYDATE="20130312" 
                TRAILERID="" 
                TRIPROUTEID="" 
                DEPOTCODE=""/>
        <RECORD TPNB="123456666" 
                NOOFCASES="" 
                OUTERCASELENGTH ="1" 
                OUTERCASEWIDTH="2"  
                OUTERCASEHEIGHT="3" 
                UNITSPERCASE="" 
                USEBYDATE="20130312121212" 
                MU="">
        </RECORD>        
    </STORE>
    <TRAILER ID="9" RECORDCOUNT=" 3" />
</MESSAGE>

我想用这个 xml 填充一个实体,我所有属于特定的记录storeid都应该组合到一个列表中。

var _preNotifiedProduct = 
        from nlist in xDocument.Descendants("RECORD")
        group nlist by nlist.Anestors("STORE").Attributes().First().Value 
        into cust
        select new {key=cust.Key,value = ??};

这里的键是我的商店 id,值应该是属于该商店 id 的类型 (XElement) RECORD 的列表。如果我分配value=cust这将显示记录 xelement 列表中的所有非公共成员元素。

如何将其放入 xelement 列表中?

4

1 回答 1

2

custimplements IEnumerable<XElement>,所以你可以调用ToList()它:

var _preNotifiedProduct = 
              from nlist in xDocument.Descendants("RECORD")
              group nlist by nlist.Ancestors("STORE").Attributes().First().Value 
              into cust
              select new
              {
                  key = cust.Key,
                  value = cust.ToList()
              };

但是,我会将您的查询重写为:

var _preNotifiedProduct = from store in xDocument.Root.Elements("STORE")
                          select new
                          {
                              key = (int)store.Attribute("ID"),
                              value = store.Elements("RECORD").ToList()
                          };

应该返回相同的值,但也应该更具可读性和效率。

于 2013-04-09T14:49:00.823 回答