How to Deserialize xml to an array of objects?
Asked Answered
M

3

3

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; }
}

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);
        }

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

Thank you

Mckee answered 24/9, 2011 at 21:2 Comment(1)
Your Rectangles xml tag is not ended. Is this a typo?Ramadan
M
9

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 );
  }
Mutilate answered 25/9, 2011 at 1:6 Comment(1)
If you'll put your FileStream into a using block, then I'll upvote your answer.Skateboard
S
1

Your XML is missing a closing </Rectangles> element. That might be the problem!

Stank answered 24/9, 2011 at 21:4 Comment(0)
T
1

The problem is about root element name.

However, Deserialize( ) only knows how to look for an element named Rectangles. But in your case element named "Rectangle". that is all the InvalidOperationException is telling you.

Tango answered 24/9, 2011 at 21:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.