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

后端 未结 7 2132
情话喂你
情话喂你 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:04

    @Blorgbeard: If you have more then one of these YesNo classes in an object class, make sure to read the entire element.

    public void ReadXml(XmlReader reader)
    {
        string element = reader.ReadOuterXml();
        int startIndex = element.IndexOf('>') + 1;
        int length = element.LastIndexOf('<') - startIndex;
    
        string text = (element.Substring(startIndex, length).ToLowerInvariant();
    
        Value = (text == "yes");
    }
    

    Otherwise this might cause problems.

    The ReadXml method must reconstitute your object using the information that was written by the WriteXml method.

    When this method is called, the reader is positioned at the start of the element that wraps the information for your type. That is, just before the start tag that indicates the beginning of a serialized object. When this method returns, it must have read the entire element from beginning to end, including all of its contents. Unlike the WriteXml method, the framework does not handle the wrapper element automatically. Your implementation must do so. Failing to observe these positioning rules may cause code to generate unexpected runtime exceptions or corrupt data.

提交回复
热议问题