Why does the XMLSerializer in C# store data of Rectangle twice?

Owen Ransen 1 Reputation point
2022-10-16T06:18:28.92+00:00

I have a Rectangle in a class:

        private Rectangle m_rcPos = new Rectangle(10, 10, 100, 100); // x,y,wide,high  
        public Rectangle rcPos  // this is for the XML read write  
        {  
            get { return m_rcPos; }  
            set { m_rcPos = value; }  
        }  
  

When I serialize the class the size and position get serialized twice:

<rcPos>  
  <Location>  
    <X>0</X>  
    <Y>0</Y>  
    </Location>  
        <Size>  
            <Width>4000</Width>  
           <Height>2774</Height>  
        </Size>  
        <X>0</X>  
        <Y>0</Y>  
    <Width>4000</Width>  
    <Height>2774</Height>  
</rcPos>  

Is this correct? Can I stop it from happening?

(apologies for the formattng, the code editing window here does not always work..)

I imagine it is happening because the definition of Rectangle uses all possible fields... and XmlIgnore has not been used.

TIA

Owen

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,215 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 119.2K Reputation points
    2022-10-16T13:48:08.203+00:00

    To work around the problem, try this XmlSerializer:

    XmlAttributeOverrides ao = new XmlAttributeOverrides( );  
    XmlAttributes a = new XmlAttributes { XmlIgnore = true };  
    ao.Add( typeof( Rectangle ), nameof( Rectangle.Location ), a );  
    ao.Add( typeof( Rectangle ), nameof( Rectangle.Size ), a );  
      
    XmlSerializer s = new XmlSerializer( typeof( MyClass ), ao );  
    

    Use your class instead of MyClass.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.