自定义对象的xmlserializer

时间:2012-07-30 23:21:03

标签: c# xmlserializer

以下是我的xml文件的样子:

我尝试使用xsd为我的对象生成类,但是当我尝试反序列化它时,它不知何故。我需要列是一个字符串数组,我的类(对象)应该是什么,以便它可以反序列化xml。

<ArrayOfDirective>  
<Directive>
<TestCaseName>RunSqlCar</TestCaseName>
<Action>IgnoreColumn</Action>
<Columns>
<ColumnName>value1</ColumnName>
<ColulmnName>value2</ColulmnName>
</Columns>
<Description>These columns never match becuase IDs are different always.</Description>    
</Directive>
</ArrayOfDirective>

错误: 读取c:\ Directives.xml时出错:XML文档中存在错误(2,2)

1 个答案:

答案 0 :(得分:0)

使用XmlSerializer序列化的数据如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfDirective xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Directives>
    <Directive>
      <TestCaseName>RunSqlCar</TestCaseName>
      <Action>IgnoreColumn</Action>
      <Columns>
        <Column>
          <ColumnName>value1</ColumnName>
        </Column>
        <Column>
          <ColumnName>value2</ColumnName>
        </Column>
      </Columns>
      <Description>These columns never match because IDs are different always.</Description>
    </Directive>
  </Directives>
</ArrayOfDirective>

这些是序列化为上述XML的示例类。

class Program
{
    static void Main(string[] args)
    {
        ArrayOfDirective directives = new ArrayOfDirective();

        Directive directive = new Directive("RunSqlCar", "IgnoreColumn",
                "These columns never match because IDs are different always.");

        directive.Columns.Add(new Column("value1"));
        directive.Columns.Add(new Column("value2"));

        directives.Directives.Add(directive);

        XmlSerializer ser = new XmlSerializer(typeof(ArrayOfDirective));
        using (StreamWriter sw = File.CreateText("c:\\directives_generated.xml"))
        {
            ser.Serialize(sw, directives);
        }
    }
}

[Serializable]
public class ArrayOfDirective
{
    public List<Directive> Directives { get; set; }

    public ArrayOfDirective()
    {
        Directives = new List<Directive>();
    }
}

[Serializable]
public class Directive
{
    public string TestCaseName { get; set; }
    public string Action { get; set; }
    public List<Column> Columns { get; set; }
    public string Description { get; set; }

    public Directive(string testCaseName, string action, string description)
    {
        TestCaseName = testCaseName;
        Action = action;
        Description = description;
        Columns = new List<Column>();
    }

    public Directive()
    {
    }
}

[Serializable]
public class Column
{
    public string ColumnName { get; set; }

    public Column(string columnName)
    {
        ColumnName = columnName;
    }

    public Column()
    {
    }
}