Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3272274
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T18:48:33+00:00 2026-05-17T18:48:33+00:00

I have a set of .net classes that I currently serialize and use with

  • 0

I have a set of .net classes that I currently serialize and use with a bunch of other code, so the format of that xml is relatively fixed (format #1). I need to generate xml in another format (format #2) that’s a pretty similar structure but not exactly the same, and am wondering the best approach for this.

For example, say these are my classes:

public class Resource 
{ 
    public string Name { get; set; }
    public string Description { get; set; }
    public string AnotherField { get; set; }
    public string AnotherField2 { get; set; }
    public Address Address1 { get; set; }
    public Address Address2 { get; set; }
    public Settings Settings { get; set; }
}
public class Address
{ 
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
} 
// This class has custom serialization because it's sort-of a dictionary. 
// (Maybe that's no longer needed but it seemed necessary back in .net 2.0).
public class Settings : IXmlSerializable
{ 
    public string GetSetting(string settingName) { ... }
    public string SetSetting(string settingName, string value) { ... }
    public XmlSchema GetSchema() { return null; }
    public void ReadXml(XmlReader reader) 
    {
        // ... reads nested <Setting> elements and calls SetSetting() appropriately 
    }
    public void WriteXml(XmlWriter writer)
    {
        // ... writes nested <Setting> elements 
    }
} 

I normally use standard XmlSerialization and it produces great XML (format #1). Something like:

<Resource>
  <Name>The big one</Name>
  <Description>This is a really big resource</Description>
  <AnotherField1>ADVMW391</AnotherField1>
  <AnotherField2>green</AnotherField2>
  <Address1>
    <Line1>1 Park Lane</Line1>
    <Line2>Mayfair</Line2>
    <City>London</City>
  </Address1>
  <Address2>
    <Line1>11 Pentonville Rd</Line1>
    <Line2>Islington</Line2>
    <City>London</City>
  </Address2>
  <Settings>
    <Setting>
      <Name>Height</Name>
      <Value>12.4</Value>
    </Setting>
    <Setting>
      <Name>Depth</Name>
      <Value>14.1028</Value>
    </Setting>
  </Settings>
</Resource>

The new XML I want to generate (format #2) looks like the current XML, except:

  • Instead of field AnotherField and AnotherField2, these should now be represented as Settings. ie as if SetSetting() was called twice before serializing, so the values appear as new elements within .

  • Instead of fields Address1 and Address2, these should be represented as an element containing two elements. The elements should have an extra attribute or two, e.g. Position and AddressType.

e.g.

<Resource>
  <Name>The big one</Name>
  <Description>This is a really big resource</Description>
  <Addresses>
    <Address>
      <Line1>1 Park Lane</Line1>
      <Line2>Mayfair</Line2>
      <City>London</City>
      <Position>1</Position>
      <AddressType>Postal</AddressType>
    </Address>
    <Address>
      <Line1>11 Pentonville Rd</Line1>
      <Line2>Islington</Line2>
      <City>London</City>
      <Position>2</Position>
      <AddressType>Postal</AddressType>
    </Address>
  </Addresses>
  <Settings>
    <Setting>
      <Name>Height</Name>
      <Value>12.4</Value>
    </Setting>
    <Setting>
      <Name>Depth</Name>
      <Value>14.1028</Value>
    </Setting>
    <Setting>
      <Name>AnotherField</Name>
      <Value>ADVMW391</Value>
    </Setting>
    <Setting>
      <Name>AnotherField2</Name>
      <Value>green</Value>
    </Setting>
  </Settings>
</Resource>

Can I use XmlAttributeOverrides to control serialization in this way? Otherwise how should I approach it?

Bear in mind that my real classes have at least 10 times the number of fields, and there are some nested classes where I’m completely happy with the default serialization, so I’d like to avoid too much manual serialization code.

Possible Options

I can see these options:

  1. Maybe it’s possible to use overrides to control serialization of just the attributes I care about?
  2. Custom serialization of the Resource class for format #2, calling the default serialization of nested classes where appropriate. Not sure how to deal with Settings as I effectively want to add settings, serialize using default, then remove the added settings.
  3. Create xml using default serialization, then manipulate the XML to make the changes I need. (ick!).

Another slight complication is that Resource from my example above actually has two subtypes, each with a couple of extra fields. The default serialization handles this nicely. Any new method would need to deal with serializing these subtypes too. This means I’m not keen on a solution that involves me making different subtypes purely for serialization purposes.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T18:48:33+00:00Added an answer on May 17, 2026 at 6:48 pm

    I ended up solving this problem by creating a new class that did the custom serialization of attributes that needed it, then using XmlAttributeOverrides to ensure that class was used instead of the default serialization for the attribute.

    public class Resource
    { 
        ...
    
        // the method that actually does the serialization
        public void SerializeToFormat2Xml(XmlWriter writer)
        { 
            Format2Serializer.Serialize(writer, this);
        }
    
        // Cache the custom XmlSerializer. Since we're using overrides it won't be cached
        // by the runtime so if this is used frequently it'll be a big performance hit
        // and memory leak if it's not cached. See docs on XmlSerializer for more.
        static XmlSerializer _format2Serializer = null;
        static XmlSerializer Format2Serializer
        { 
            get { 
                if (_format2Serializer == null) 
                { 
                    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
                    XmlAttributes ignore = new XmlAttributes();
                    ignore.XmlIgnore = true;
    
                    // ignore serialization of fields that will go into Settings 
                    overrides.Add(typeof (Resource), "AnotherField", ignore);
                    overrides.Add(typeof (Resource), "AnotherField2", ignore);
    
                    // instead of serializing the normal Settings object, we use a custom serializer field
                    overrides.Add(typeof (Resource), "Settings", ignore);
                    XmlAttributes attributes = new XmlAttributes();
                    attributes.XmlIgnore = false;
                    attributes.XmlElements.Add(new XmlElementAttribute("Settings"));
                    overrides.Add(typeof (Resource), "CustomSettingsSerializer", attributes);
    
                    // ... do similar stuff for Addresses ... not in this example
    
    
                    _format2Serializer = new XmlSerializer(typeof(Resource), overrides);
               }
               return _format2Serializer;
            }
        }
    
        // a property only used for custom serialization of settings
        [XmlIgnore]
        public CustomSerializeHelper CustomSettingsSerializer
        {
            get { return new CustomSerializeHelper (this, "Settings"); }
            set { } // needs setter otherwise won't be serialized!
        }
    
        // would have a similar property for custom serialization of addresses, 
        // defaulting to XmlIgnore.
    }
    
    
    public class CustomSerializeHelper : IXmlSerializable
    {
        // resource to serialize
        private Resource _resource;
    
        // which field is being serialized. 
        private string _property;
    
        public CustomSerializeHelper() { } // must have a default constructor
        public CustomSerializeHelper(Resource resource, string property)
        {
            _resource = resource;  
            _property = property;  
        }
    
        public XmlSchema GetSchema()
        {
            return null;
        }
    
        public void ReadXml(XmlReader reader)
        {
            return;
        }
    
        public void WriteXml(XmlWriter writer)
        {
            if (_property == "Settings")
            {
                Dictionary<string, string> customSettings = new Dictionary<string, string>();
                customSettings.Add("AnotherField", _resource.AnotherField);
                customSettings.Add("AnotherField2", _resource.AnotherField2);
    
                _resource.Settings.WriteXml(writer, customSettings);
            }
            if (_property == "Addresses")
            { 
                // ... similar custom serialization for Address, 
                // in that case getting a new XmlSerializer(typeof(Address)) and calling
                // Serialize(writer,Address), with override to add Position.
            }
        }
    
    
    public partial class Settings
    { 
        // added this new method to Settings so it can serialize itself plus
        // some additional settings.
        public void WriteXml(XmlWriter writer, Dictionary<string, string> additionalSettingsToWrite)
        {
            WriteXml(writer);
            foreach (string key in additionalSettingsToWrite.Keys)
            {
                string value = additionalSettingsToWrite[key];
                writer.WriteStartElement("Setting");
                writer.WriteElementString("SettingType", key);
                writer.WriteElementString("SettingValue", value);
                writer.WriteEndElement();
            }
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using ASP.NET MVC RC2. I have a set of classes that were auto-generated
I have a set of classes that I've written in C++ for a code
I have a set of .NET components that were developed long ago (1.1). I
I have an existing set of .net libraries that I wish to call from
I have set up my website to use ASP.NET Membership. it all works fine
I have set in my mastersite of my asp.net application the following that the
Could I use migrator.net bare migration framework and just have a set of SQL
Currently, we use a giant configuration object that is serialized to/from XML. This has
I have an ASP .NET Web Forms application that makes use of the 'WebMethod'
I have a property in one of the classes I created that currently has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.