如何从xml读取数据并从类实例

时间:2015-08-07 06:59:00

标签: c# xml class

我是c#的新手(对于Windows应用程序),我试图理解我在网络上找到的一个例子。

有一个课程:

public class Person
{
    string firstname;
    string lastname;
    int age;

    public string FirstName
    {
        get { return firstname; }
        set { firstname = value; }
    }

    public string LastName
    {
        get { return lastname; }
        set { lastname = value; }
    }

    public int Age
    {
        get { return age; }
        set { age = value; }
    }
}

一个从XML读取数据并将其绑定到列表框的代码:

string peopleXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "Assets/PeopleData.xml");
XDocument loadedData = XDocument.Load(peopleXMLPath);

var data = from query in loadedData.Descendants("person")
           where (int)query.Element("age") == 27
           select new Person
           {
               FirstName = (string)query.Element("firstname"),
               LastName = (string)query.Element("lastname"),
               Age = (int)query.Element("age")
           };
listBox.ItemsSource = data;

但是如何将(例如)FirstName转换为字符串变量以在TextBox.text中使用它?我如何在数据集中移动下一个?

1 个答案:

答案 0 :(得分:2)

LINQ查询返回IEnumerable<something>,在您的情况下为IEnumerable<Person>。您可以迭代结果以获取每个值。

foreach (var item in data)
{
    MessageBox.Show(item.FirstName);
    // or in console app
    //Console.WriteLine(item.FirstName);
}