开发者

Group a XElement into a collection in Linq to XML?

This is an XML example:

<ProblemFactory Name="Diagnostic exam" Count="1">
    <Condition ObjectiveID="1" Type="1" CountRanges="2" Range1Decimals="0" Range1Min="3" Range1Max="10" Range2Decimals="0" Range2Min="6" Range2Max="10" />
    <Condition ObjectiveID="1" Type="1开发者_JAVA技巧" CountRanges="2" Range1Decimals="0" Range1Min="6" Range1Max="10" Range2Decimals="0" Range2Min="6" Range2Max="10" />
</ProblemFactory>

And I'm trying to do something like the following:

        XDocument xdoc = XDocument.Load("ProblemFactory.xml");
        var problems = from pf in xdoc.Descendants("Condition")
                       select new
                       {
                           // ObjectiveID property
                           // Type property
                           // Ranges collection property
                       };

Create the ranges collection is my problem. How can I strutured my XML file or query to create the collection? The collection will contain: RangeDecimals, RangeMin, RangeMax.

I'm not sure, but I can Imagine to solve this problem I've gotta reestruct my Condition tuple:

<Condition ObjectiveID="1" Type="1" >
    <RangesCollection>
        <Range RangeDecimals="0" RangeMin="3" RangeMax="10" />
        <Range RangeDecimals="0" RangeMin="6" RangeMax="10" />
    </RangesCollection>
</Condition>


var problems = 
    from condition in xdoc.Descendants("Condition")
    select new {
        ObjectiveID = condition.Attribute("ObjectiveID").Value,
        Type = condition.Attribute("Type").Value,
        Ranges = Enumerable
            .Range(1, (int)condition.Attribute("CountRanges"))
            .Select(i => new {
                Min = (int)condition.Attribute("Range" + i + "Min"),
                Max = (int)condition.Attribute("Range" + i + "Max"),
                Decimals = (int)condition.Attribute("Range" + i + "Decimals"),
            }).ToArray()
    };


With the new format,

Ranges = condition.Descendants("Range")
    .Select(range => new {
        Min = (int)range.Attribute("RangeMin"),
        Max = (int)range.Attribute("RangeMax"),
        Decimals = (int)range.Attribute("RangeDecimals")
    })
    .ToArray()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜