What happens if you leave out the IsNullable = true? (I don't have 2.0 on
the machine I'm on right now so can't check how 2.0 handles this.)
The following will certainly do the type of thing you are looking for
though:
public class AccountNullable
{
private int? _AcctID;
public int? AcctID
{
get { return _AcctID; }
set { _AcctID = value; }
}
[XmlIgnore]
public bool AcctIDSpecified
{
get
{
return AcctID.HasValue;
}
}
}
By adding a bool property for each property XXX of the form XXXSpecified
that returns XXX.HasValue, the framework will not serialize the property if
it is null.
[quoted text, click to view] <christopherkilmer@gmail.com> wrote in message
news:1138730585.638863.103190@f14g2000cwb.googlegroups.com...
> I'm doing a little R&D. I've got a simple object:
>
> public class AccountNullable
> {
> private int? _AcctID;
>
> private string _AcctName;
>
> [XmlElementAttribute(IsNullable = true)]
> public int? AcctID
> {
> get { return _AcctID; }
> set { _AcctID = value; }
> }
>
> public string AcctName
> {
> get { return _AcctName; }
> set { _AcctName = value; }
> }
> }
>
> I want to be able to serialize this object and have any property that
> is null be left out of the resulting xml.
>
> For example, the result of
>
> AcctName = null
> AcctID = 1234
>
> would be
>
> <AccountNullable>
> <AcctID>1234</AcctID>
> </AccountNullable>
>
> and, the result of
>
> AcctName = "Joe Programmer"
> AcctID = null //this is a nullable integer type
>
> would be
>
> <AccountNullable>
> <AcctName>Joe Programmer</AcctName>
> </AccountNullable>
>
> However, when the result I get when AcctID is set to null is this:
>
> <AccountNullable>
> <AcctID xsi:nil="true"/>
> <AcctName>Joe Programmer</AcctName>
> </AccountNullable>
>
> Is it possible to serialize this object so that the propertys that are
> null are excluded from the serialized xml instead of included with the
> xsi:nil="true" attribute? Any help would be appreciated.
>
> BTW, here is the code I used to test:
>
> class Program
> {
> static void Main(string[] args)
> {
> try
> {
> AccountNullable an = new AccountNullable();
> Serialize(an);
>
> an.AcctName = "Jane Dough";
> Serialize(an);
>
> an.AcctID = 12345;
> Serialize(an);
>
> Console.ReadLine();
> }
> catch (Exception ex)
> {
> Log(String.Format("{0}, {1}", ex.Message,
> ex.StackTrace));
> }
>
> Console.ReadLine();
> }
>
> private static void Serialize(AccountNullable a)
> {
> StringWriter wr = new StringWriter();
> XmlSerializer sr = new
> XmlSerializer(typeof(AccountNullable));
>
> //Serialize object into an XML string
> sr.Serialize(wr, a);
> string xml = wr.ToString();
> wr.Close();
>
> Log(xml);
>
> }
>
> private static void Log(string msg)
> {
> Console.WriteLine(String.Format("{0}{1}", msg,
> Environment.NewLine));
> }
> }
>