问题:
一个xml文件:
格式:<people name="xxx" age="123"></people>
<people name="aaa" age="456"></people>
c#的people对象:class people
{
 public people(){}
 public name;
 public age;……
}
c#分析xml里每个people的属性,name和age。foreach (XmlElement Node in people) 
          {
                 //这里为每个people新建一个people对象
                XmlAttributeCollection attCol = Node.Attributes;
                foreach (XmlAttribute xAtt in attCol )
                 {  
                         //这里面为新建对象的name和age赋值。
                 }
          }
我希望最后这段代码里能新建不同名的对象,且对象可以在外面使用。请问怎么做?谢谢了

解决方案 »

  1.   

    主要意思是:
    为xml里的每个people建一个对象。
      

  2.   

    创建一个 People类的集合,在循环中把New出来的对象放置到集合中
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Collections;namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private void Form1_Load(object sender, EventArgs e)
            {
                List<People> Peoples= new List<People>();
                for (int i = 0; i < 10; i++)
                {
                    People p = new People();
                    p.Name = i.ToString();
                    p.Age = i;
                    Peoples.Add(p);
                }
                MessageBox.Show(Peoples[0].Name);
            }
        }    public class People
        {
            private string _name;
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
            private int _age;
            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }
        }
    }
      

  3.   

    XmlDocument   xmlDoc   =   new   XmlDocument(); 
    xmlDoc.Load(""); 
    XmlNode   xmlNode   =  xmlDoc.SelectSingleNode(""); 
    List<People> lst=new List<People>();
    XmlAttributeCollection   xmlAttr = xmlNode.Attributes; 
    for   (int   i   =   0;   i   <  xmlAttr.Count;   ++i) 
     { 
      People p=new People();
      if (xmlAttr.Item(i).Name.Euals("name") 
             p.name=   xmlAttr.Item(i).Value; 
     lst.Add(p);
     } 
      

  4.   

    LList<People> Peoples= new List<People>();
     Peoples.Add(p);没错没错~~