Serialize class to XML?

ぃ、小莉子 提交于 2019-12-18 03:36:10

问题


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

public class Transport
{
    public string TransportType { get; set; }
    public string Mode { get; set; }
    public class Coordinates
    {
        public float ID { get; set; }
        public float LocX { get; set; }
        public float LocY { get; set; }
        public float LocZ { get; set; }
        public ObjectState State { get; set; }
        public List<int[]> Connections = new <int[]>();
    }
}

public enum ObjectState
{
    Fly,
    Ground,
    Water
}

public static List<Transport> Tracking = new List<Transport>();

How do I serialize the Tracking to XML ?

I know I can use [Serializable] on the list and serialize it to file but I am not sure on how I define it to be saved as XML.


回答1:


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
}



回答2:


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.



来源:https://stackoverflow.com/questions/5937630/serialize-class-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!