Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

c# - Serialize class to 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>();

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...