1

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;

    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
4

1 回答 1

1

XML反序列化需要第一行

<?xml version="1.0" encoding="utf-8"?>

如果要将部分 xml 文档转换为 Object,则必须将此行附加到部分 XML 的顶部。

另外,您需要使用 XmlRootAttribute 装饰 Apple 类,其中 ElementName 将为“Apple”

本文介绍如何设置 XmlRootAtrribute http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute.aspx

希望这会有所帮助

问候。

于 2010-11-09T07:51:48.450 回答