如何使 XML 可序列化? [英] How to make an XML Serializable?

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

问题描述

我有一个需要序列化的 XML 文件.我使用了 VS 特性 Paste Special->Convert XML to C# Classes 特性并获得了该 XML 文件的 C# 类.

I had an XML File that I needed to serialize. I used VS feature Paste Special->Convert XML to C# Classes feature and got the C# classes for that XML file.

XML 的 C# 文件有多个类,如下图所示:

The C# file for the XML has Multiple Classes as shown in the image below:

生成的C#XML的结构如下

The generated C# of XML has the following structure

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://example.com/633")]
        [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://example.com/633", IsNullable = false) ]

        public partial class FlightPlan
        {

            private FlightPlanM633Header m633HeaderField;

            private FlightPlanM633SupplementaryHeader m633SupplementaryHeaderField;
------
-----
}

我想添加 [serializable] 属性并继续序列化整个 XML.我无法添加 [serializable] 属性.

I want to add the [serializable] attribute and go ahead with the serializing the whole XML. I am unable to add [serializable] attribute.

推荐答案

Paste Special > Paste Xml As Classes 命令已经添加了 SerializableAttribute 它创建的类,所以没有需要自己添加.您应该能够立即进行序列化:

The Paste Special > Paste Xml As Classes command already adds the SerializableAttribute the classes it creates so no need to add them yourself. You should be able to serialization straight away:

using System;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var serializer = new XmlSerializer(typeof(FlightPlan));

            // Deserialize
            FlightPlan o = (FlightPlan)
                serializer.Deserialize(new StreamReader("source.xml"));

            // Serialize
            serializer.Serialize(new StreamWriter("Out.xml"), o);
        }
    }
}

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

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