使用 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()
{
}
}