How can I get XmlSerializer to encode bools as yes/no?

后端 未结 7 2200
情话喂你
情话喂你 2020-12-31 05:49

I\'m sending xml to another program, which expects boolean flags as \"yes\" or \"no\", rather than \"true\" or \"false\".

I have a class defined like:



        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 06:23

    Very simple. Use a surrogate property. Apply XmlIgnore on the actual property. The surrogate is a string, and must use the XmlElement attribute that takes a element-name override. Specify the name of the actual property in the override. The surrogate property serializes differently based on the value of the actual property. You must also provide a setter for the Surrogate, and the setter should set the actual property appropriately, for whatever value it serialized. In other words it needs to go both ways.

    Snip:

        public class SomeType 
        {
    
            [XmlElement]
            public int IntValue;
    
            [XmlIgnore]
            public bool Value;
    
            [XmlElement("Value")]
            public string Value_Surrogate {
                get { return (Value)? "Yes, definitely!":"Absolutely NOT!"; }
                set { Value= (value=="Yes, definitely!"); }
            }
    
        }
    

    click here for full compilable source example.

提交回复
热议问题