如何将 xml 反序列化为对象数组?
我正在尝试将 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; }
}
我创建了几个矩形,将它们保存到一个数组中并设法将它们序列化为 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>
-
现在我想要将矩形对象反序列化回新的矩形[] 我应该怎么做?
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的 XML 文档有效,您应该能够使用以下代码对其进行反序列化:
If your XML document is valid, you should be able to use this codes to deserialize it:
您的 XML 缺少结束
元素。这可能就是问题所在!
Your XML is missing a closing
</Rectangles>
element. That might be the problem!问题在于根元素名称。
然而,Deserialize() 只知道如何查找名为 Rectangles 的元素。
但在你的例子中,元素名为“矩形”。这就是 InvalidOperationException 告诉您的全部内容。
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.