将数据从XML文件导入字符串
本文关键字:导入 字符串 文件 XML 数据 | 更新日期: 2023-09-27 18:21:52
我已经搜索了24小时的答案,但没有找到。我是C#的新手。我找到了一个教程,从那里我使用了这个代码:
XDocument loadedCustomData = XDocument.Load("PeopleCustom.xml");
var filteredData = from c in loadedCustomData.Descendants("Person")
where c.Attribute("Age").Value == current.ToString()
select new Person
{
FirstName = (string)c.Attribute("FirstName").Value,
};
listBox1.ItemsSource = filteredData;
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是这样的:
<People>
<Person
FirstName="Kate"
LastName="Smith"
Age="1" />
<Person
...
/>
</People>
它可以工作,但它将所有输出放入列表框中。我想要绳子。我试图从列表框中获取字符串(如listBox1.Items[0].ToString();),但我得到的只是这样的东西:ProjectName.MainPage+Person。我也试图从filteredData中得到它,但没有成功。有什么方法可以将数据从XML转换为字符串吗?提前感谢您的回答
此代码
XDocument loadedCustomData = XDocument.Load("PeopleCustom.xml");
var filteredData = from c in loadedCustomData.Descendants("Person")
where c.Attribute("Age").Value == current.ToString()
select new Person
{
FirstName = (string)c.Attribute("FirstName").Value,
};
制作Person对象列表:select New Person{.....}
若您想要一个Person
名字的字符串列表,那个么您所要做的就是更改LINQ正在创建的对象。。。。
select (string)c.Attribute("FirstName").Value );
现在,它从FirstName
属性中生成一个新字符串。
在运行这个linq之后,您基本上将有一个linq对象,它将生成一个字符串列表。如果你想要一个列表,那么修改如下:
XDocument loadedCustomData = XDocument.Load("PeopleCustom.xml");
var filteredData =( from c in loadedCustomData.Descendants("Person")
where c.Attribute("Age").Value == current.ToString()
select (string)c.Attribute("FirstName").Value ).ToList();
如果您想要列表中的第一个字符串。。。
filterdData.First();
从输出中,您将获得listBox1.items包含person对象,因此您可以尝试
var name = ((Person)listBox1.Items[0]).FirstName;
这将为您提供值