How to deserialize xml for an array of objects?

I am trying to deserialize an 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 in an array, and was able to serialize them in xml. I got 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 to the new rectangle [] how should I do this?

 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 InvalidOperationException - {"There is an error (1, 40) in the XML document." } what am I doing wrong?

thanks

+3
c # deserialization xml-serialization xml-deserialization
source share
3 answers

If your XML document is valid, you can use these codes to deserialize:

  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 ); } 
+9
source share

Your XML does not have a closing element </Rectangles> . This can be a problem!

+1
source share

The problem is the name of the root element.

However, Deserialize () only knows how to look for an element named Rectangles. But in your case, the item is called the Rectangle. this is all an InvalidOperationException tells you.

+1
source share

All Articles