Serialize class to XML?

后端 未结 2 1735
粉色の甜心
粉色の甜心 2020-12-16 04:18

I have the follow class and the list that holds it:

public class Transport
{
    public string TransportType { get; set; }
    public string Mode { get; set;         


        
相关标签:
2条回答
  • 2020-12-16 04:37

    You need a stream and a XmlSerializer object, here's an example:

    FileStream fs = new FileStream(@"C:\MyPath", FileMode.OpenOrCreate);
    
    xmlSerializer = new XmlSerializer(typeof(MyClass));
    
    xmlSerializer.Serialize(fs, myClassInstance);
    
    fs.Flush();
    fs.Close();
    fs.Dispose();
    

    Don't forget to handle errors your own way. And I'm also assuming you want to serialize all your class' properties.

    0 讨论(0)
  • 2020-12-16 04:56

    If both of your classes were tagged with the [Serializable] attribute, then saving things to a file should be as simple as:

    var serializer = new XmlSerializer(typeof(Transport));
    
    using(var writer = new StreamWriter("C:\\Path\\To\\File.xml"))
    {
        serializer.Serialize(writer, instance);
    }
    

    Update

    Sorry, didn't realize you were asking about how to customize the output. That is what the [XmlAttribute] and [XmlElement] attributes are for:

    public class Transport
    {
        // Store TransportType as an attrribute called Type in the XML
        [XmlAttribute("Type")]
        public string TransportType { get; set; }
    
        // Rest of Implementation
    }
    
    0 讨论(0)
提交回复
热议问题