简体   繁体   English

XML反序列化

[英]XML Deserialization

I have an xml file which is in this format 我有一个这种格式的xml文件

"<rundate>

  <rundateItem>
    <LeaveCreditingMonth>2</LeaveCreditingMonth>
    <LeaveCreditingYear>2010</LeaveCreditingYear>
    <IncludeNoTimesheet>True</IncludeNoTimesheet>
  </rundateItem>

</rundate>"

in case i want to deserialize this xml file, what should be the format of the class or the target object of my deserialization? 如果我想反序列化该xml文件,反序列化的类或目标对象的格式应该是什么? Currently my class looks like this: 目前,我的课程如下所示:

public class rundate
    {

        string _leaveCreditingMonth;
        string _leaveCreditingYear;
        string _includeNoTimesheet;

        public string LeaveCreditingMonth {get{return _leaveCreditingMonth;}set{ _leaveCreditingMonth = value;}}
        public string LeaveCreditingYear {get{return _leaveCreditingYear;}set{ _leaveCreditingYear = value;}}
        public string IncludeNoTimesheet {get{return _includeNoTimesheet;}set{ _includeNoTimesheet = value;}}

    }

Your class can stay as is (obviously you should change the data types to be appropriate though) - since you have rundate nested in your XML (which implies there can be more than one) I would suggest adding a collection class as follows: 你的类可以继续担任是(很明显,你应该改变的数据类型,虽然是合适的) -因为你已经rundate嵌套在你的XML(这意味着可能有不止一个)我会建议增加一个集合类,如下所示:

[XmlRoot("rundate")]
public class RundateCollection
{
    [XmlElement("rundateItem")]
    public List<rundate> Rundates { get; set; }
}

You can test serializing/deserializing your class with your XML as follows: 您可以使用XML测试序列化/反序列化类,如下所示:

XmlSerializer serializer = new XmlSerializer(typeof(RundateCollection));
StringWriter sw = new StringWriter();
rundate myRunDate = new rundate() { LeaveCreditingMonth = "A", IncludeNoTimesheet = "B", LeaveCreditingYear = "C" };
RundateCollection ra = new RundateCollection() { Rundates = new List<rundate>() { myRunDate } };
serializer.Serialize(sw, ra);
string xmlSerialized = sw.GetStringBuilder().ToString();
string xml = File.ReadAllText(@"test.xml");
StringReader sr = new StringReader(xml);
var rundateCollection = serializer.Deserialize(sr);

You will see that the collection class is successfully deserialized from your XML and contains one list item of type runlist . 您将看到该收集类已成功从XML反序列化,并且包含一个runlist类型的列表项。

I would design the class like so: 我会像这样设计课程:

public class Rundate
    {

        public int LeaveCreditingMonth { get; set;}
        public int LeaveCreditingYear { get; set; }
        public bool IncludeNoTimesheet { get; set; }

    }

Then you can deserialize it like this: 然后,您可以像这样反序列化它:

var serializer = new XmlSerializer(typeof(List<Rundate>));
using (var fs = new FileStream("yourfile.xml", FileMode.Open))
{
    using (var reader = new XmlTextReader(fs))
    {
        var rundates = (List<Rundate>)serializer.Deserialize(reader);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM