Results 1 to 3 of 3

Thread: [RESOLVED] Serialize a property only if it has a value

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2006
    Location
    Madrid
    Posts
    325

    Resolved [RESOLVED] Serialize a property only if it has a value

    Hi,
    I´m trying to serialize objects in C# to Xml.

    Is there a way, only to serialize a property if its value is different to null or nothing?

    So, it its value is null, then not to serialize.

    Thanks!

  2. #2

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2006
    Location
    Madrid
    Posts
    325

    Re: Serialize a property only if it has a value

    Sorry I forgot to mention, that the property is returning a List.
    So by default it always returns a set of outer tags.

    For instance;

    Code:
    public class cars
        {
    
            public cars()
            {
    
            }
    
            public cars(string carName)
            {
                this.CarName = carName;
                this.carList.Add(testCar);
            }
    
            string name;
            List<cars> carList = new List<cars>();
    
            [System.Xml.Serialization.XmlArrayAttribute("CarListTest")]
            public List<cars> carlist
            {
                get
                {
                    return this.carList;
                }
            }
    
        }
    Even though the List<cars> is empty, it always returns a set of outer tags.

    What I´d like is, that if List<cars> is empty, then not to export no xml, not even outer tags.

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2006
    Location
    Madrid
    Posts
    325

    Re: Serialize a property only if it has a value

    Amazing but true,

    I really do not know why this works!

    But if you add the following method;

    Code:
    public bool ShouldSerialize<property>
              {
                  return carList.Count > 0;
              }
    In this case;

    Code:
    public bool ShouldSerializecarlist()
              {
                  return carList.Count > 0;
              }
    It will only serialize carlist if it has a count>0

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width