我有以下XML,我将其加载到XDocument
<ConversionSpecification xmlns="http://tempuri.org/X12ParserSpecification.xsd" TransactionSetIdentifierCode="837">
<Loop LoopId="1000A" Name="SNAME" Identifier="NM1*41">
<Segment SegmentId="NM1" Usage="R"/>
<Segment SegmentId="PER" Usage="R"/>
</Loop>
<Loop LoopId="1000B" Name="RNAME" Identifier="NM1*40">
<Segment SegmentId="NM1" Usage="R"/>
</Loop>
<Loop LoopId="2000B" Name="SHLOOP" Identifier="22">
<Segment SegmentId="SBR" Usage="R"/>
<Segment SegmentId="PAT" Usage="S"/>
</Loop>
</ConversionSpecification>
XDocument document = XDocument.Load("Files/Loops.xml");
XNamespace ns = XNamespace.Get("http://tempuri.org/X12ParserSpecification.xsd");
var loopInfo = from loop in document.Descendants(ns + "Loop")
select new Loop
{
LoopID = loop.Attribute("LoopId").Value,
LoopIdentifier = loop.Attribute("Identifier").Value
LoopSegments =
LoopUsage =
};
Loop在哪里:
class Loop
{
public string LoopID { get; set; }
public string LoopIdentifier { get; set; }
public string[] LoopSegments { get; set; }
public string[] LoopUsage { get; set; }
}
现在我想为LoopElements分配SegmentID属性值,并为LoopUsage分配使用属性值。有没有办法用一个子查询来做到这一点?
答案 0 :(得分:0)
这就是你要追求的吗?
var loopInfo = from loop in document.Descendants(ns + "Loop")
select new Loop
{
LoopID = loop.Attribute("LoopId").Value,
LoopIdentifier = loop.Attribute("Identifier").Value,
LoopSegments = loop.Descendants(ns + "Segment").Select(s => s.Attribute("SegmentId").Value).ToArray(),
LoopUsage = loop.Descendants(ns + "Segment").Select(s => s.Attribute("Usage").Value).ToArray()
};
输出如下: