c# linq to xml XElement按祖先属性分组,创建带有键的实体集合列表
本文关键字:创建 列表 集合 实体 xml to linq XElement 属性 祖先 | 更新日期: 2023-09-27 18:08:20
我有下面的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列表中?
cust
实现了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()
};
应该返回相同的结果,但也应该更具可读性和效率。