简体   繁体   English

C#XML LINQ查询到LIST <>

[英]C# XML LINQ Query to LIST<>

I'm trying to turn an XML document into a List<> with a predefined Class 我正在尝试将XML文档转换为具有预定义类的List <>

My xml dataset TestData.xml 我的xml数据集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. 看起来LINQ Query查找数据但从未将其分配给List<Test> myTest,该值在调试器中显示为null。 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. 我想将XML转换为List<Test>以便可以随机重新排列对象。 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<> . 我只是使用int []数组并按“ID”排序,但我不知道数组的实际长度,并且想要动态分配它,所以我被迫做一个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") . 没有经过测试,我认为你应该编写TestData.Descendants("Object")而不是TestData.Descendants("Objects") The parameter for Descendants must match the name of the nodes you want to select. Descendants的参数必须与您要选择的节点的名称匹配。

You are already at the root that is Objects 你已经是Objects的根

Do this 做这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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