简体   繁体   中英

C# XML LINQ Query to LIST<>

I'm trying to turn an XML document into a List<> with a predefined Class

My xml dataset TestData.xml

<Objects>
    <Object ID="1">
        <ItemOne>"Hickory"</ItemOne>
        <ItemTwo>"Dickory"</ItemTwo>
        <ItemThree>"Dock"</ItemThree>
    </Object>

    <Object ID="2">
        <ItemOne>"The"</ItemOne>
        <ItemTwo>"Mouse"</ItemTwo>
        <ItemThree>"Went"</ItemThree>
    </Object>
</Objects>

The Main program

class Program
{
    static void Main(string[] args)
    {

        XElement TestData = XElement.Load("TestData.xml");

       List<Test> myTest = new List<Test>(from d in TestData.Descendants("Objects")
                                     select new Test(
                                         d.Element("ItemOne").Value.ToString(),
                                         d.Element("ItemTwo").Value.ToString(),
                                         d.Element("ItemThree").Value.ToString()));

        myTest.ForEach(i => Console.WriteLine("{0} {1} {2}", i.itemOne, i.itemTwo, i.itemThree));

        Console.ReadLine();
    }


}

The class I'm trying to form the data to

class Test
{
    public string itemOne { get; set; }
    public string itemTwo { get; set; }
    public string itemThree { get; set; }
}

I would like to get out

Hickory Dickory Dock
The Mouse went

but I end up getting nothing. It looks like the LINQ Query finds the data but never assigns it to the List<Test> myTest, the value shows as null in the debugger. I'm not sure what I'm doing wrong.

I want to convert the XML to List<Test> so I can randomly rearrange through the objects. I was going to just use int[] array and sort by "ID" but I don't know the actual length of the array and want to assign it on the fly so I am forced to do a list<> . I am open to other suggestions of accomplishing this.

Without having it tested, I think you should write TestData.Descendants("Object") instead of TestData.Descendants("Objects") . The parameter for Descendants must match the name of the nodes you want to select.

You are already at the root that is Objects

Do this

from d in TestData.Descendants("Object")
                               --------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM