XML序列化器和反序列化器 [英] Xml serializer and Deserializer

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

问题描述

你好,

我有一个xml文件,其中保存了许多序列化对象(由xmlserializer自动执行). 序列化"文件时是否可以排除某些对象?

我不确定我是否可以自我解释,所以请询问是否不清楚.

谢谢,
Sas Gabriel

Hello,

I have a xml file in which a lot of serialized objects are saved (automatically by the xmlserializer). Is it possible to exclude some objects when "serializing" the file?

I''m not really sure if I explained my self okay, so please ask if something isn''t clear.

Thanks,
Sas Gabriel

推荐答案

这取决于您要解决方案的灵活性. XmlIgnore属性 [
It depends on how flexible you want your solution. The XmlIgnore attribute[^] can be used if you know at compile time what should and what shouldn''t get serialized.


Gabriel Sas,

如果我了解您的要求,那么您希望从xml读取字段的值,而不在序列化期间写入字段的值.如果您不想自己进行序列化(编写一些满足您需要的读/写方法-或其他),也许我有个主意:使用XmlIgnore和第二个字段的组合进行序列化.看这个例子:
警告:我不是说这是一个好主意,也不应该那样做,这只是我的第一个想法进行的一次小尝试,并且似乎可以奏效...

Hi Gabriel Sas,

If I understand you rigth you want a field''s value to be read from xml but not written during serialization. If you don''t want to do the serialization yourself (write some read/write methods fitting your needs - or whatever) maybe I have an idea: Use combination of XmlIgnore and a second field for serialization. Look at this example:
Caution: I don''t say this is an good idea or should be done like that, was just a little experiment from my first thought, and seems to work...

using System;
using System.IO;
using System.Xml.Serialization;

namespace ExcludeOnlyFromSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            const string m_strPATH = "Test.xml";
            // create a sample object
            SampleClass sampleobject = new SampleClass() { SomeString = "Test", SomeInteger = 987, SomeBoolean = true };
            Console.WriteLine(sampleobject);

            // serialize it
            Save(sampleobject, m_strPATH);

            // - and deserialize into a new object 
            SampleClass sampleobjectNew = Load(m_strPATH);
            Console.WriteLine(sampleobjectNew);

            Console.ReadKey();
        }

        static SampleClass Load(string strFilePath)
        {
            SampleClass scLoaded = null;

            if (File.Exists(strFilePath))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(SampleClass));
                using (FileStream filestream = new FileStream(strFilePath, FileMode.Open))
                {
                    try
                    {
                        scLoaded = (SampleClass)serializer.Deserialize(filestream);
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        filestream.Close();
                    }
                }
            }

            return scLoaded;
        }


        static void Save(SampleClass sc, string strFilePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(SampleClass));

            using (TextWriter textwriter = new StreamWriter(strFilePath))
            {
                try
                {
                    serializer.Serialize(textwriter, sc);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    textwriter.Close();
                }
            }
        }

    }

    public class SampleClass
    {
        [XmlIgnore]
        public string SomeString { get; set; }
        public int SomeInteger { get; set; }
        public bool SomeBoolean { get; set; }

        string m_strSomeStringDeserializeOnly = "This is serialized";
        public string SomeStringReadOnly
        {
            get { return m_strSomeStringDeserializeOnly; }
            set { SomeString = value; }
        }

        public override string ToString()
        {
            return String.Format("{0}({3}), {1}, {2}", SomeString, SomeInteger, SomeBoolean, SomeStringReadOnly);
        }
    }
}



因此,如果序列化SampleClass对象,则会忽略SomeString,但会写入SomeStringDeserializeOnly.如果反序列化"SampleClass"对象,则将读取SomeStringDeserializeOnly的值并将其设置为SomeString属性(在SomeStringDeserializeOnly属性的set-accessor中完成).
我希望这对您有用,但令我困惑的是您为什么要这样做?我可以回顾几年"的专业编码和无数序列化方案,但是我从未遇到过非微调序列化的需求-如果您想读回一些东西,无论如何都必须写另一个值……是吗?确定这是您需要的吗? (很抱歉,如果我完全误解了您,但是我已经做到了这一点-使用常规属性并进行序列化/反序列化-并在反序列化之后只分配非写入/读取"属性(对此使用XMLIgnore)).



So if you serialize a SampleClass-object, SomeString is ignored, but SomeStringDeserializeOnly is written. If you deserialize a "SampleClass"-object, the value of SomeStringDeserializeOnly is read and set to the SomeString property (done in the set-accessor of SomeStringDeserializeOnly property).

I hope this is useful to you, but what puzzles me is why you want to do that? I can look back to "some years" of professional coding and countless serialization scenarios, but I never came across such a requirenment for non fine tuned serialization - You have to write another value anyway if you want to read something back... Are you shure this is what you need? (sorry if I completly missunderstood you, but I''d have done it like this - use a normal property and serialize/deserialize - and just assign the "non written/but read" property (use XMLIgnore on that) after deserialization).


我建​​议使用数据合约.这种方式是最不介入的.要序列化的成员甚至不必是公共的,也不必实现任何接口.您只需要标记类型和成员并使用属性将其表示为合同的一部分.

请参阅
http://msdn.microsoft.com/en-us/library/ms733127.aspx [ ^ ].

请在我倡导这种方法的地方查看我过去的答案:
如何在我的表单应用程序? [ ^ ],
创建属性文件... [反序列化json字符串数组 [
I recommend to use Data Contract. This way is the most non-intrusive. The members to be serialized do not even have to be public, don''t have to implement any interfaces. You only need to mark types and members with attributes which indicate them as being a part of contract.

Please see http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

Please also see my past answers where I advocate this approach:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^],
deseralize a json string array[^].

—SA


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

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