0

我有以下代码,现在我在控制台窗口中获取查询输出没有任何问题,但我想将它放在 Listview 中。我不知道该怎么做.. :)

这是我的 XML 数据:

<?xml version="1.0" encoding="utf-8" ?>
<Student>
 <Person name="John" city="Auckland" country="NZ" />
 <Person>
    <Course>GDICT-CN</Course>
    <Level>7</Level>
    <Credit>120</Credit>
    <Date>129971035565221298</Date>
 </Person>
 <Person>
    <Course>GDICT-CN</Course>
    <Level>7</Level>
    <Credit>120</Credit>
    <Date>129971036040828501</Date>
 </Person>
</Student>

以下是我的代码:

List<string> list1=new List<string>();

private void button1_Click(object sender, EventArgs e)
{
    string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    XDocument xDoc = XDocument.Load(path + "\\Student Data\\data.xml");

    //IEnumerable<XElement> rows = from row in xDoc.Descendants("Person")
    //                             where (string)row.Attribute("Course") == "BICT"
    //                             select row;
    string i = textBox1.Text;

    IEnumerable<XElement> rows = 
        xDoc.Descendants()
            .Where(d => d.Name == "Person" && 
                        d.Descendants().Any(e => e.Name == "ID" &&
                                                 e.Value == i)
            );

    foreach (XElement xEle in rows)
    {
        IEnumerable<XAttribute> attlist = 
            from att in xEle.DescendantsAndSelf().Attributes() 
            select att;

        foreach (XAttribute xatt in attlist)
        {
            string n = xatt.ToString();
            //Console.WriteLine(xatt);
            list1.Add(n);
        }
        foreach (XElement elemnt in xEle.Descendants())
        {
            Console.WriteLine(elemnt.Value);
            list1.Add(elemnt.Value);
        }
        //Console.WriteLine("-------------------------------------------");

    }
    //Console.ReadLine();
    listView1.Items.Add(); // I am not sure.... 
}
4

2 回答 2

0

MSDN 中介绍了在运行时向 ListView 添加项目:http: //msdn.microsoft.com/en-us/library/aa983548 (v=vs.71).aspx

// Adds a new item with ImageIndex 3
listView1.Items.Add("List item text", 3);

如果您没有任何图像,只需将索引设置为 0。

于 2012-11-11T12:49:49.647 回答
0

创建ListViewItems以将结果添加到ListView. ListViewItem接受字符串数组。第一个是项目的文本。其他是子项(在详细视图模式下可见)

var items = from p in xdoc.Descendants("Person")
            select new ListViewItem(
                new string[] {
                    (string)p.Attribute("name"),
                    (string)p.Element("Course"),
                    (string)p.Element("Level")     
                }
                );

foreach(var item in items)
     listView.Items.Add(item);
于 2012-11-11T12:50:22.027 回答