将 InnerXML 反序列化为 .NET 中的对象

发布于 2024-09-30 23:32:53 字数 2257 浏览 5 评论 0原文

我正在处理一个包含无限集合的大型 xml 文件。其想法是使用 XmlReader 读取文件并将内部 xml 反序列化为对象并进行进一步处理。

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>

使用 XMLReader 包装 XMLTextReader 来读取文件,一切都很顺利。但是,当我尝试将单个苹果反序列化为对象时,它会抛出 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放我走吧 2024-10-07 23:32:53

XML 反序列化需要第一行为

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

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

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

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

希望这会对

您有所帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文