0

这是我的 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)

4

1 回答 1

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()
    {
    }
}
于 2012-07-31T01:13:56.030 回答