动态创建分层XML结构

时间:2013-05-09 17:13:12

标签: .net xml c#-2.0 xmldocument xmlnode

我正在创建一个XML,如下面的代码所示

public class Group
{
[XmlElement(typeof(Manager))]
public Employee [] Staff;

[XmlElement (typeof(int)),
XmlElement (typeof(string)),
XmlElement (typeof(DateTime))]
public ArrayList ExtraInfo;
}

public class Employee
{
public string Name;
}

public class Manager:Employee
{
public int Level;
}

public class Run 
{
public static void Main()
{
  Run test = new Run();
  test.SerializeObject("TypeEx.xml");
}

public void SerializeObject(string filename)
{
     // Create an XmlSerializer instance.
  XmlSerializer xSer = 
  new XmlSerializer(typeof(Group));

  // Create object and serialize it.
  Group myGroup = new Group();

  Manager e1 = new Manager();
  e1.Name = "Manager1";
  Manager m1 =  new Manager();
  m1.Name = "Manager2";
  m1.Level = 4;

  Employee[] emps = {e1, m1};
  myGroup.Staff = emps;

  myGroup.ExtraInfo = new ArrayList();
  myGroup.ExtraInfo.Add(".NET");
  myGroup.ExtraInfo.Add(42);
  myGroup.ExtraInfo.Add(new DateTime(2001,1,1));

  TextWriter writer = new StreamWriter(filename);
  xSer.Serialize(writer, myGroup);
  writer.Close();
  }
  } 

在“http://msdn.microsoft.com/en-IN/library/system.xml.serialization.xmlelementattribute.type(v=vs.80).aspx”分享。在这种情况下,我在员工中添加了2个“e1”和“m1”的经理。但如果我必须在循环中添加5个管理器,我更新了以下代码: 经理[] a =新经理[5];

    for (int i = 0; i < 5; i++)
    {
        a[i] = new Manager();
        a[i].Name = "temp" + i;
        a[i].Level = i;
    }
    Employee[] empss = new Employee[5];

    for (int k = 0; k < 5; k++)
    {
        empss[k] = new Employee();
        myGroup.Staff = empss[k]; // line25
    } 

但是它给了我以下错误:“不能在第25行隐式地将类型'Employee'转换为'Employee []'”。任何人都可以建议我如何纠正它?

0 个答案:

没有答案