سؤال

I'm hoping someone can help answer this for me, as I've been pulling my hair out all morning trying to track down a solution to this issue.

I have a class that needs to be serialized to XML. The XML Serialization works as long as I'm serializing a simple public property. However, if I have a public property that acts as a getter for a private field that backs it, the public property isn't serialized (despite being decorated with [XmlAttribute()]). I've combed through MSDN and StackOverflow looking for answers, but to no avail. I've mocked up an example below.

[Serializable()]
[XmlRoot("foobar")]
public class FooBar
{
     [XmlAttribute("foo")]
     public string Foo { get; set; }
     private bool bar;
     [XmlAttribute("bar")]
     public string Bar 
     {
          get { return ConvertBoolToYesNo(bar); }
     }

    public FooBar()
    {
         Foo = "foo";
         bar = true;
    } 

    public string ConvertBoolToYesNo(bool boolToConvert)
    {
         if(boolToConvert == true)
              return "yes";
         else
              return "no";
    }

}

This returns <?xml version="1.0" encoding="us-ascii"?><foobar foo="foo" /> when I would expect it to return <?xml version="1.0" encoding="us-ascii"?><foobar foo="foo" bar="yes" />. Any suggestions would be appreciated.

Thanks in advance!

هل كانت مفيدة؟

المحلول

Check this answer right here:

Why are properties without a setter not serialized

Seems like it is a serializer limitation (by design) when you have "readonly" properties, try adding a "setter" and it might work.

نصائح أخرى

I believe that read-only properties could not be seriazlied by XMLSerializer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top