如何将xml反序列化为对象数组? [英] How to Deserialize xml to an array of objects?

查看:129
本文介绍了如何将xml反序列化为对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将xml文件反序列化为对象[]-该对象是具有以下字段的矩形

I am tryind to deserialize a xml file into an object[] - the object is a rectangle with the following fields

public class Rectangle : IXmlSerializable
{
    public string Id { get; set; }
    public Point TopLeft { get; set; }
    public Point BottomRight { get; set; }
    public RgbColor Color { get; set; }
}

我创建了几个矩形,将它们保存到数组中并设法对其进行序列化到xml中,我得到以下语法:

I created several rectangles, saved them into an array and managed to serialize them into the xml i get the following syntax:

<?xml version="1.0" encoding="utf-8" ?> 
- <Rectangles>
 - <Rectangle>
    <ID>First one</ID> 
  - <TopLeft>
    <X>0.06</X> 
    <Y>0.4</Y> 
    </TopLeft>
  - <BottomRight>
    <X>0.12</X> 
    <Y>0.13</Y> 
    </BottomRight>
  - <RGB_Color>
    <Blue>5</Blue> 
    <Red>205</Red> 
    <Green>60</Green> 
    </RGB_Color>
  </Rectangle>

-

现在我想反序列化矩形对象重新变成新的矩形[]
我应该怎么做?

Now i want to deserialize the rectangle objects back into a new rectangle[] how should i do it?

XmlSerializer mySerializer = new XmlSerializer(typeof(Rectangle));
        FileStream myFileStream = new FileStream("rectangle.xml", FileMode.Open);
        Rectangle[] r = new Rectangle[] {};
        Rectangle rec;
        for (int i = 0; i < 3; i++)
        {
            r[i] = (Rectangle) mySerializer.Deserialize(myFileStream);
        }

我得到一个InvalidOperationException-{ XML文档中有一个错误(1 ,40)。}
我在做什么错了?

i get a InvalidOperationException - {"There is an error in XML document (1, 40)."} what am i doing wrong?

谢谢

推荐答案

如果您的XML文档有效,则应该可以使用以下代码对其进行反序列化:

If your XML document is valid, you should be able to use this codes to deserialize it:

  XmlSerializer mySerializer = new XmlSerializer( typeof( Rectangle[] ), new XmlRootAttribute( "Rectangles" ) );
  using ( FileStream myFileStream = new FileStream( "rectangle.xml", FileMode.Open ) )
  {
    Rectangle[] r;
    r = ( Rectangle[] ) mySerializer.Deserialize( myFileStream );
  }

这篇关于如何将xml反序列化为对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆