开发者

how do i parse this xml in one linq statement

<Fruit>
    <Apple>
        <Pear>dar</Pear>
        <Orange/>
        <Starfruit>har</Starfruit>
    </Apple>
    <Lemon>
        <Melon>yar</Melon>
        <Lime>blah</Lime>
    </Lemon>
<Fruit>

At the moment I have two select statements and then storing the values from those two separate enumerations into an object.

        var myfruits = from myfruit in document.Descendants("UserAccount")
                   select new
                   {
                       Pear= myfruit.Element("Pear").Value,
                       Starfruit= myfruit.Element("Starfruit").Val开发者_如何学Pythonue,

                   };
        var myfruits2 = from myfruit2 in document.Descendants("Product")
                    select new
                    {
                        Melon= myfruit2.Element("Melon").Value,
                        Lime= myfruit2.Element("Lime").Value,
                    };
        foreach (var myfruit in myfruits)
        {
            megafruit.Pear=myfruit.Pear;
            megafruit.Starfruit=myfruit.Starfruit;
        }
        foreach (var myfruit2 in myfruits2)
        {
            megafruit.Melon= myfruit2.Melon;
            megafruit.Lime= myfruit2.Lime;
        }
        return megafruit;


You can navigate the XML document when you expand the query results (since you have a collection of all the descendant nodes). Something like this:

XDocument document = XDocument.Parse("<Fruit><Apple><Pear>dar</Pear><Orange/><Starfruit>har</Starfruit></Apple><Lemon><Melon>yar</Melon><Lime>blah</Lime></Lemon></Fruit>");

var megafruit = (from x in document.Descendants("Fruit")
                 select new
                 {
                     Pear = x.Element("Apple").Element("Pear").Value,
                     Orange = x.Element("Apple").Element("Orange").Value,
                     Starfruit = x.Element("Apple").Element("Starfruit").Value,
                     Melon = x.Element("Lemon").Element("Melon").Value,
                     Lime = x.Element("Lemon").Element("Lime").Value
                 }).SingleOrDefault();

This will generate an anonymous class that has the properties filled with the values of the supplied XML. Alternatively, you can also use select new Megafruit() rather than just select new - which would create a new instance of the Megafruit class with the properties set according to the XML.

Note that this is a very simple example, assuming one occurrence of each of the fruits - it's similiar to something I did at work many moons ago, where I knew the data I was getting was not going to be a collection (like a collection fo pears, or oranges, or whatever) so I coudl use SingleOrDefault.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜