将数据从XML文件导入到字符串

时间:2012-01-31 02:05:22

标签: c# xml string

我一直在寻找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获取到字符串?提前感谢您的回答

2 个答案:

答案 0 :(得分:1)

此代码

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对象,它将生成一个字符串列表。如果你想要一个List,那么修改如下:

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();

答案 1 :(得分:0)

从输出中你得到listBox1.items包含人物对象,所以你可以尝试

var name = ((Person)listBox1.Items[0]).FirstName;

这应该给你值