[英]How to Deserialize xml to an array of objects?
I am tryind to deserialize a xml file into an object[] - the object is a rectangle with the following fields 我试着将xml文件反序列化为对象[] - 该对象是一个带有以下字段的矩形
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我得到以下语法:
<?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? 我得到一个InvalidOperationException - {“XML文档中有一个错误(1,40)。”}我做错了什么?
Thank you 谢谢
If your XML document is valid, you should be able to use this codes to deserialize it: 如果您的XML文档有效,您应该能够使用此代码对其进行反序列化:
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 );
}
Your XML is missing a closing </Rectangles>
element. 您的XML缺少结束
</Rectangles>
元素。 That might be the problem! 那可能就是问题!
The problem is about root element name. 问题是根元素名称。
However, Deserialize( ) only knows how to look for an element named Rectangles. 但是,Deserialize()只知道如何查找名为Rectangles的元素。 But in your case element named "Rectangle".
但在你的case元素名为“Rectangle”。 that is all the InvalidOperationException is telling you.
这就是所有InvalidOperationException告诉你的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.