我正在處理包含無限集合的大型XML文件。這個想法是使用XmlReader讀取文件並將內部xml反序列化爲一個對象並進行進一步處理。將.NET反序列化爲.NET中的對象
的XML結構是這樣的:
<Basket xmlns="http://AppleFarm.com/Basket">
<AppleCount>10000</AppleCount>
<Apples>
<Apple><ID>1</ID><Color>Red</Color></Apple>
<Apple><ID>2</ID><Color>Green</Color></Apple>
...
<Apple><ID>10000</ID><Color>Green</Color></Apple>
</Apples>
</Basket>
一切順利使用XmlTextReader的周圍包裹的XMLReader讀取文件。然而,當我試圖將個別蘋果反序列化爲對象時,它會拋出InvaildOperationException。
任何人都知道最新的問題?有沒有更好的方法來做到這一點?
下面是代碼片段
//Deserialize code
public object Deserialize(XmlDocument doc, Type type){
using(XmlNodeReader reader - new XmlNodeReader(doc.DocumentElement)){
XmlReaderSetting settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.None;
using(XmlReader xReader = XmlReader.Create(reader, settings)){
XmlSerializer serializer = new XmlSerializer(type);
object obj = serializer.Deserialize(xReader);
}
}
}
public void GetApples(string filepath){
XmlTextReader reader = new XmlTextReader(filepath);
while(reader.Read()){
while(reader.NoteType == XmlNodeType.Element &&
reader.Name == "Apple"){
XmlDocument doc = new XmlDocument();
doc.LoadXml(reader.ReadOuterXml());
Apple a = (Apple)Deserialize(doc, typeof(Apple));
//...
}
}
}
//Deserialize code end
//Apple class
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.XmlSerialization.XmlTypeAttribute(Namespace="http://AppleFarm.com/Basket")]
public partial class Apple{
private string idField;
private string colorField;
public string Id{
get{ return this.idField; }
set{ this.idField = value; }
}
public string Color{
get { return this.colorField; }
set { this.colorField = value; }
}
}
//Apple class end
你可以發佈反序列化的代碼和Apple類的代碼嗎? – Oded 2010-11-08 10:33:19
我已經添加了xml的代碼和名稱空間。 – Blithe 2010-11-09 06:22:51
應該ID爲ID? – 2010-11-09 06:41:57