English 中文(简体)
是否将类序列化为XML?
原标题:Serialize class to XML?

我有下面的类和包含它的列表:

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

如何将Tracking序列化为XML?

我知道我可以在列表中使用[Serializable]并将其序列化到文件中,但我不确定如何将其定义为XML。

最佳回答

如果您的两个类都使用[Serializable]属性进行了标记,那么将内容保存到文件中应该非常简单:

var serializer = new XmlSerializer(typeof(Transport));

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

更新

很抱歉,没有意识到您在询问如何自定义输出。这就是[XmlAttribute][EXmlElement]

public class Transport
{
    // Store TransportType as an attrribute called Type in the XML
    [XmlAttribute("Type")]
    public string TransportType { get; set; }

    // Rest of Implementation
}
问题回答

您需要一个流和一个XmlSerializer对象,下面是一个示例:

FileStream fs = new FileStream(@"C:MyPath", FileMode.OpenOrCreate);

xmlSerializer = new XmlSerializer(typeof(MyClass));

xmlSerializer.Serialize(fs, myClassInstance);

fs.Flush();
fs.Close();
fs.Dispose();

不要忘记用自己的方式处理错误。我还假设您希望序列化所有的类属性。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...