以下是我迄今为止与由第三方DLL返回的XmlDocument一起使用的步骤:
- 我将XmlDocument保存为SegmentationSummary.xml。
- 我使用XSD.exe创建了SegmentationSummary.xsd。
- 我使用XSD.exe创建了SegmentationSummary.cs。
以下是SegmentationSummary.cs的示例。请注意,ShmResult是根节点表示。
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "omitted")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "omitted", IsNullable = false)]
public partial class ShmResult
{
private ShmResultDownloadDetail[] downloadDetailField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("DownloadDetail")]
public ShmResultDownloadDetail[] DownloadDetail
{
get
{
return this.downloadDetailField;
}
set
{
this.downloadDetailField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "omitted")]
public partial class ShmResultDownloadDetail
{
private string modelCodeField;
/// <remarks/>
public string ModelCode
{
get
{
return this.modelCodeField;
}
set
{
this.modelCodeField = value;
}
}
}
现在,我想使用它来读取XmlDocument并开始使用SegmentationSummary.cs中的类。这是我编写的代码:
private XmlDocument _document;
SegmentationSummary.ShmResult _Result;
private void LoadXML()
{
XmlReader xmlRdr = new XmlNodeReader(_document);
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(SegmentationSummary.ShmResult));
_Result = (SegmentationSummary.ShmResult)s.Deserialize(xmlRdr);
}
当执行LoadXML()时,我会遇到以下类型的异常:
测试方法SegmentationSummaryHandlerTest.TestMethod1引发了异常:System.InvalidOperationException: 无法生成临时类(result = 1)。错误CS0030:无法将类型'MERC.AIRCAT.SHMCoreInterface.SegmentationSummary.ShmResultDownloadDetail []'转换为'MERC.AIRCAT.SHMCoreInterface.SegmentationSummary.ShmResultDownloadDetail'。错误CS0029:无法隐式将类型'MERC.AIRCAT.SHMCoreInterface.SegmentationSummary.ShmResultDownloadDetail'转换为'MERC.AIRCAT.SHMCoreInterface.SegmentationSummary.ShmResultDownloadDetail []'
现在,http://msdn.microsoft.com/en-us/library/ms950721.aspx上的常见问题解答如下:
问:如何序列化对象集合?
答:当集合包含未在XmlSerializer构造函数中声明的类型时,XmlSerializer会抛出异常。您可以:
1.通过传递Type[]来向序列化程序声明类型,以便在集合中使用。
或者
2.实现一个从System.Collections.CollectionBase派生的强类型集合,并使用与Add()方法匹配的索引器。
我的问题是:哪种方法最好,我该如何实现解决方案?