有没有办法做到的对象(其属性)序列化到XML?
-
23-08-2019 - |
题
创建类(称之为FormElement)。这类应该有像它们与数据元素中的元数据的一些属性(名称,序列号,值 - 这只是一个字符串等)。
此类有作为类型验证应用程序块的验证类的属性。
我想要序列它XML和反序列化。验证类包括验证应用程序块属性的所有属性生存序列化。
一些建议?
没有正确的解决方案
其他提示
在.NET框架有这种内置的,用C#你会做这样的:
// 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文件返回到一个类的实例的示例:
// 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输出多一点漂亮,你可以使用[XmlElement的]和[XmlAttribute]在你的类属性的属性,让他们序列化到您所选择的模式。
这是说序列化,你的意思是使用官方的序列化机制,或达到类似的效果?
如果你的对象是豆,你可以使用反射来写,需要一个类,并写下它的类名和属性的通用服务。它可以同样地从XML读取的材料和产生对象(这是Apache的沼气池基本上一样)。
什么乔纳森荷兰说。
不过,你也问验证。如果你正确地使用代码乔纳森贴,你的所有属性的将会的序列化和反序列化。但如果你真的想看看,有你可以用一个*的.xsd架构验证对你XmlSerializer对象设置属性。您可以通过使用附带Visual Studio中的xsd.exe
命令行工具创建架构从你的类很轻松了。
此外,这听起来像你可能想要控制你的类的某些属性是否序列化为属性或元素。乔纳森触及,但我想显示的示例:
[Serializable]
public class FormElement
{
[XmlAttribute]
public string Name {get; set;};
[XmlAttribute]
public int Sequence {get; set;};
[XmlAttribute]
public string Value {get; set;};
[XmlElement]
public Validation OnValidate{get; set;}
[NonSerialized]
public string UnimportantProperty {get; set;};
}
最后,对于每个属性,你要序列也必须是可序列化复杂类型的类型,并且必须序列化为XmlElements。否则,你将无法做到这一点。
XStream的是这样做仅仅是一个相当不错的java库。
不隶属于 StackOverflow