有没有办法做到的对象(其属性)序列化到XML? [英] Is there a way to do object (with its attributes) serializing to xml?

查看:110
本文介绍了有没有办法做到的对象(其属性)序列化到XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个类(称之为FormElement)。这个类应该有像他们有数据元素的元数据的一些属性(名称,序列号,价值,它只是一个字符串,等等)。

Create a class (call it FormElement). That class should have some properties like the metadata they have with data elements (name, sequence number, value—which is just a string, etc).

本类有类型验证应用程序块的验证类的属性。

This class has as attributes of type Validation Application Block Validation classes.

我想序列化到XML和反序列化。验证类,包括验证应用程序块属性的所有属性生存序列化。

I want to serialize it to xml and deserialize it. Verify that all properties of the class including the validation application block attributes survive serialization.

一些建议吗?

推荐答案

在.NET框架有这种内置的,使用C#,你会做这样的:

The .NET framework has this built in, using C# you would do it like this:

// This code serializes a class instance to an XML file:
XmlSerializer xs = new XmlSerializer(typeof(objectToSerialize));

using (TextWriter writer = new StreamWriter(xmlFileName))
{
     xs.Serialize(writer, InstanceOfObjectToSerialize);
}

和这个片段是如何反序列化的XML文件恢复到一个类的实例的例子:

And this snippet is an example of how to deserialize an XML file back to a class instance:

// this code creates a class instance from the file we just made:
objectToSerialize newObject;
XmlSerializer xs = new XmlSerializer(typeof(objectToSerialize));

using (TextReader reader = new StreamReader(xmlFileName))
{
    newObject = (ObjectToSerialize) xs.Deserialize(reader);
}

您必须使用[Serializable]属性的这些工作,你的类。如果你想使你的XML输出​​多一点pretty的,你可以使用[的XmlElement]和[XmlAttribute]在你的类属性的属性将它们序列化到您所选择的模式。

You must mark your class with the [Serializable] attribute for these to work. If you want to make your XML output a little more pretty, you can use [XmlElement] and [XmlAttribute] attributes on your class properties to have them serialize into your schema of choice.

这篇关于有没有办法做到的对象(其属性)序列化到XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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