Neeraj Kumar
Neeraj Kumar

Reputation: 57

How to ignore Empty Values during XMLSerilization in C#?

I am fetching Data from the DB. If the DBObject data has empty value ("") not null then I want to exculde that value from the XML Serilization.

  EventComment event = new EventComment();
        event.Comments = datalogic.GetComment();

    if(event.Comments != String.Empty){
    //Add Logic
    }
SerializeToXmL(event)
    //dataLogic Class
        public string GetComment()
                {
                    var datalink = _unitOfWork.GetRepository<tbl1>()
                                 .GetFirstOrDefault(predicate: source => (source.id == id));
        
        
                    return datalink .comment;
                }

I know we can use null value but i do not want to assign null value to the variable. Can I get diffrent solution from null. I am getting empty tag as of now after XML serilization.

<comment/>

Upvotes: 1

Views: 432

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062855

null values are already excluded; if we're talking about ignoring empty strings (""), then "conditional serialization" is your friend. Many serializers (including XmlSerializer) support this via a well-known public bool ShouldSerialize*() pattern, for example:

public class Foo
{
    [XmlElement("comment")]
    public string Comment { get; set; }

    public bool ShouldSerializeComment() => !string.IsNullOrEmpty(Comment);
}

If I serialize this with an empty Comment: the Comment member is not serialized. You can trivially extend this to apply any other logic you like, for example:

public bool ShouldSerializeComment() => !string.IsNullOrWhiteSpace(Comment);

Upvotes: 1

Related Questions