Click here to Skip to main content
14,883,954 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Posted
Updated 12-Jan-12 1:49am
v4
Comments
Suraj S Koneri 12-Jan-12 7:32am
   
you want to change one of them means and you dont need to change the file..what it means?
Gabriel Sas 12-Jan-12 7:41am
   
i modified the question

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


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).
   
Comments
Gabriel Sas 12-Jan-12 11:55am
   
it works, Thanks
johannesnestler 12-Jan-12 13:05pm
   
nice to hear - good luck with your project!
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.
   
Comments
Gabriel Sas 12-Jan-12 10:32am
   
i want that attribute to get it's value from the xml file but when i save the objects to xml i dont want the tag <example> from this object in my .xml file

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900