[英]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 ? 如何将跟踪序列化为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]并将其序列化为文件,但我不确定如何定义它以保存为XML。
If both of your classes were tagged with the [Serializable]
attribute, then saving things to a file should be as simple as: 如果您的两个类都使用[Serializable]
属性进行标记,那么将文件保存到文件应该非常简单:
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: 这就是[XmlAttribute]
和[XmlElement]
属性的用途:
public class Transport
{
// Store TransportType as an attrribute called Type in the XML
[XmlAttribute("Type")]
public string TransportType { get; set; }
// Rest of Implementation
}
You need a stream and a XmlSerializer object, here's an example: 你需要一个流和一个XmlSerializer对象,这是一个例子:
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. 我还假设您要序列化所有类的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.