序列化类XML? [英] Serialize class to XML?

查看:121
本文介绍了序列化类XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有后续类和持有该列表:

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>();



我如何序列化跟踪到XML?

How do I serialize the Tracking to XML ?

我知道我可以使用[Serializable接口]的名单上,序列化到文件,但我不知道我如何定义它保存为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.

推荐答案

如果双方你的类被标记与 [Serializable接口] 属性,然后保存的东西到一个文件应该是简单的:

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);
}



更新

对不起,不知道你问的有关如何自定义输出。这正是 [XmlAttribute] [的XmlElement] 属性是:

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
}

这篇关于序列化类XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆