【问题标题】:serialize an object with its attribute to xml [duplicate]将具有其属性的对象序列化为xml [重复]
【发布时间】:2008-12-26 15:29:51
【问题描述】:

完全重复:Is there a way to do object (with its attributes) serializing to xml?

颇具讽刺意味的是,它与发帖人之前的问题重复。


我想创建一个对象,它包含一些验证应用程序块属性,例如: [可序列化] 公共类 FormElement:IValidated {

    [StringLengthValidator(1, 50, MessageTemplate = "The Name must be between 1 and 50 characters")]
    public String username
    {
        get;
        set; 
    }

    [RangeValidator(2007,RangeBoundaryType.Inclusive,6000,RangeBoundaryType.Inclusive,MessageTemplate="input should be in 2007 to 6000")]
    public int sequencenumber
    {
        get;
        set;
    }

    [RegexValidator(@"^\d*\.{0,1}\d+$", MessageTemplate = "input value can not be empty or negative")]
    public string medicalvalue
    {
        get;
        set;
    }

}

如何将这些属性序列化为 xml?谢谢

【问题讨论】:

    标签: xml serialization


    【解决方案1】:

    使用 XmlSerializer 类:

    //Create serializer instance, passing in the type of the class 
    XmlSerializer serializer = 
      new XmlSerializer(typeof(FormElement));
    // Create a FileStream to write with (could be any other stream)
    Stream writer = new FileStream(filename, FileMode.Create);
    // Serialize the object, and close the TextWriter
     serializer.Serialize(writer, i);
    writer.Close();
    

    根据我的经验,序列化错误非常明显,如果您也反序列化并希望处理错误,则 XmlSerializer 类有一些有用的事件可以连接。

    【讨论】:

      【解决方案2】:

      您想将您的 Class 序列化为 XML。它不会序列化单个属性或元素。

      使用this class 来完成您需要的工作,但请谨慎使用。有时很难解决反序列化对象时发生的错误。这可能很重要,用户需要更改 XML 文件(配置等)并且不正确。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多