创建一个类(称之为FormElement)。该类应该具有一些属性,例如它们与数据元素(名称,序列号,值 - 只是一个字符串等)的元数据。
此类具有Validation Application Block Validation类的类型属性。
我想将它序列化为xml并反序列化它。验证包括验证应用程序块属性的类的所有属性是否在序列化后继续存在。
有些建议吗?答案 0 :(得分:3)
.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]属性将它们序列化到您选择的模式中。
答案 1 :(得分:0)
通过说序列化,你的意思是使用官方的序列化机制,还是达到类似的效果?
如果您的对象是bean,则可以使用反射来编写接受类的常规服务并写下其类名和属性。它可以类似地从XML中读取材料并生成对象(这是Apache Digester本质上所做的)。
答案 2 :(得分:0)
Jonathon Holland说的话。
但是,您还询问了验证。如果您使用Jonathan发布的代码,则所有属性将正确序列化和反序列化。但是,如果您确实想要检查它,则可以使用XmlSerializer对象设置一个属性,以便* .xsd架构进行验证。您可以使用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。否则你将无法做到。
答案 3 :(得分:-1)
XStream是一个非常好的java库。