DataSet的Xml序列化问题
MSDN中指出,DataSet序列化是要调用WriteXml产生。但是当我们的一个类中包含有一个类型为DataSet的属性时,直接使用XmlSerializer来做Serialize产生的XML文件中,DataSet是必然带有schema信息的。这样是无可厚非的,如果不这样是无法反序列化的。
可是我们也许有时需要DataSet生成的XML只包括数据,并不关系结构。这样就需要写一个DataSet派生类,同时为了实现XML序列化,需要实现IXmlSerializable接口 class MyDataSet : DataSet, IXmlSerializable
除了默认的构造函数,我们需要一个通过DataSet构造MyDataSet的构造函数
public MyDataSet(DataSet inputDs)
{
this.DataSetName = inputDs.DataSetName;
this.Prefix = inputDs.Prefix;
this.Namespace = inputDs.Namespace;
this.Locale = inputDs.Locale;
this.CaseSensitive = inputDs.CaseSensitive;
this.EnforceConstraints = inputDs.EnforceConstraints;
for(int index = 0; index < inputDs.Tables.Count; index++)
this.Tables.Add(new DataTable(inputDs.Tables[index].TableName));
this.Merge(inputDs, false, MissingSchemaAction.Add);
}
{
this.DataSetName = inputDs.DataSetName;
this.Prefix = inputDs.Prefix;
this.Namespace = inputDs.Namespace;
this.Locale = inputDs.Locale;
this.CaseSensitive = inputDs.CaseSensitive;
this.EnforceConstraints = inputDs.EnforceConstraints;
for(int index = 0; index < inputDs.Tables.Count; index++)
this.Tables.Add(new DataTable(inputDs.Tables[index].TableName));
this.Merge(inputDs, false, MissingSchemaAction.Add);
}
可以通过实现的IXmlSerializable接口函数WriteXml写出不带架构的XML
public new void WriteXml(XmlWriter writer)
{
this.WriteXml(writer, XmlWriteMode.IgnoreSchema);
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
{
this.WriteXml(writer, XmlWriteMode.IgnoreSchema);
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
另,如果还需要反序列化,那么还要实现ReadXml,这样就可以把xml反读回到DataSet中,不过原DataSet的很多结构信息就丢掉了。
public new void ReadXml(XmlReader reader)
{
XmlTextReader tr = reader as XmlTextReader;
bool flag = true;
bool hasTables = false;
if(tr != null)
{
flag = tr.Normalization;
tr.Normalization = false;
this.DataSetName = tr.Name;
hasTables = tr.Read();
}
if(hasTables)
this.ReadXml(tr,XmlReadMode.Auto);
if(tr != null)
tr.Normalization = flag;
}
{
XmlTextReader tr = reader as XmlTextReader;
bool flag = true;
bool hasTables = false;
if(tr != null)
{
flag = tr.Normalization;
tr.Normalization = false;
this.DataSetName = tr.Name;
hasTables = tr.Read();
}
if(hasTables)
this.ReadXml(tr,XmlReadMode.Auto);
if(tr != null)
tr.Normalization = flag;
}