XmlSerializer的自定义对象
这里是我的xml文件看起来像:XmlSerializer的自定义对象
我试图用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)
回答:
你的数据,使用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()
{
}
}
以上是 XmlSerializer的自定义对象 的全部内容, 来源链接: utcz.com/qa/261145.html