morrog
morrog

Reputation: 714

.NET XmlIgnore By Default?

Is there a way to have XmlSerializer ignore all members by default, unless I say otherwise?

I have a base class and several derived classes with lots of members, but most I do not want to be serialized. Only a select few are acceptable for serialization.

Upvotes: 4

Views: 3630

Answers (2)

SwDevMan81
SwDevMan81

Reputation: 50028

You could implement IXMLSerializable and determine what you want to be serialized. Here is an example of Object serialization. Check out this SO post about the proper way to implement IXMLSerializable. Here is an example of IXMLSerializable using for some collections.

It would look something like this:

using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace ConsoleApplicationCSharp
{
  public class ObjectToSerialize : IXmlSerializable
  {
    public string Value1;
    public string Value2;
    public string Value3;   
    public string ValueToSerialize;
    public string Value4;
    public string Value5;

    public ObjectToSerialize() { }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
      writer.WriteElementString("Val", ValueToSerialize);
    }

    public void ReadXml(System.Xml.XmlReader reader) 
    {
        if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Event")
        {
            ValueToSerialize = reader["Val"];
            reader.Read();
        }        
    }
    public XmlSchema GetSchema() { return (null); }
    public static void Main(string[] args)
    {
      ObjectToSerialize t = new ObjectToSerialize();
      t. ValueToSerialize= "Hello";
      System.Xml.Serialization.XmlSerializer x = new XmlSerializer(typeof(ObjectToSerialize));
      x.Serialize(Console.Out, t);
      return;
    }
  }
}

Upvotes: 1

marc_s
marc_s

Reputation: 755391

No, you cannot do this.

The XmlSerializer is using a "opt-out" process - it will serialize everything (all public properties) unless you explicitly opt-out by using the [XmlIgnore] attribute. There's no way of changing this behavior.

The .NET 3.5 DataContractSerializer on the other hand is taking the other approach - opt-in. It will not serialize anything, unless you specifically tell it to, by decorating your members with [DataMember].

So maybe the DataContract serializer would work for you? It was a few more advantages (doesn't require a parameter-less constructor, can serialize internal and private properties, too, and it can also serialize fields instead of properties, if needed), and it's tuned for speed. There's some downsides, too - it doesn't support attributes in XML nodes - so you'll have to pick based on your requirements.

There's a good comparison of the two by Dan Rigsby - check it out!

Marc

Upvotes: 4

Related Questions