I am working with a large xml file containing unbounded collections. The idea is to use XmlReader to read the file and to deserialize the inner xml into an object and do further processing.
The XML structure is something like this:
<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>
Everything goes well using XMLReader wrapping around XMLTextReader to read the file. However when I tried to deserialize individual apple into an object it throws InvaildOperationException.
Anyone knows whats the problem? Is there a better way to do it?
Here are the code fragments
//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;
开发者_Python百科 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
XML deserializing need first line to be
<?xml version="1.0" encoding="utf-8"?>
If you want to convert a part of xml document to Object you will have to append this line at top of the partial XML.
Plus you need to decorate Apple class with XmlRootAttribute where ElementName will be 'Apple'
this article describe how to set XmlRootAtrribute http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute.aspx
Hope this will help
Reagards.
精彩评论