1

I am trying to create a Conditional XML, using the method mentioned in Conditional xml serialization

However, it works perfectly fine in case of Strings, but If I add another data type such as Int32 or float, then the default value 0 is inserted into the XML even without assigning any value to it.

Here is my Code.

public class Books
{
    public String BookName;
    [XmlElement("Book")]
    public List<Book> BookList;
}

public class Book
 {
    [XmlAttribute] public string Title {get;set;}
    public bool ShouldSerializeTitle() {
        return !string.IsNullOrEmpty(Title);
    }

    [XmlAttribute] public Single FloatValue { get; set; }
    public bool ShouldSerializeisFloatValue()
    {
       if (FloatValue == 0.0)
         return false;
       return true;
    }     

    [XmlAttribute] public Int32 IntValue { get; set; }
    public bool ShouldSerializeInt32()
    {
      if (IntValue <= 0)
        return false;
      return true;
    }
}

and this is how I have used it.

Books books = new Books();
books.BookList = new List<Book>();
books.BookName = "My Book";

Book book1 = new Book();
book1.Title = "t1";
book1.FloatValue = 1.0F;
books.BookList.Add(book1);

Book book2 = new Book();
book2.Description = "d2";
book2.IntValue = 12;
books.BookList.Add(book2);

var serializer = new XmlSerializer(books.GetType());
String xmlFileName = @"C:/Test.xml";
TextWriter writer = new StreamWriter(xmlFileName);
serializer.Serialize(writer, books);

and this is the XML I got

-<Books>
<BookName>My Book</BookName>
<Book IntValue="0" FloatValue="1" Title="t1"/>
<Book IntValue="12" FloatValue="0" Description="d2"/>
</Books>

I wanted that in first case, IntValue Attribute shouldn't be there and in second line, Float Value Shouldn't be there in my XML.

Community
  • 1
  • 1
Pankaj
  • 2,618
  • 3
  • 25
  • 47

1 Answers1

1

I guess your ShouldSerialize* methods names should be like this (they don't match with property names in your code) :

 [XmlAttribute] public Single FloatValue { get; set; }
    public bool ShouldSerializeFloatValue()
    {
       if (FloatValue == 0.0)
         return false;
       return true;
    }     

    [XmlAttribute] public Int32 IntValue { get; set; }
    public bool ShouldSerializeIntValue()
    {
      if (IntValue <= 0)
        return false;
      return true;
    }
}
jbl
  • 15,179
  • 3
  • 34
  • 101