The properties in font are readonly and font cannot be inherited, so serialization and deserialization of font will be a little more troublesome.
You need to write a fontserializer class to implement font serialization and deserialization. Write test firstCode:
[Testmethod ()] public void fontserializationtest () {const string _ anyfilename = @ "D:/fontserializertest. XML "; xmltextwriter writer = new xmltextwriter (_ anyfilename, null); writer. formatting = formatting. indented; string name = "font"; font = new font ("Arial", 9, fontstyle. bold | fontstyle. italic | fontstyle. strikeout | fontstyle. underline); fontserializer. writexml (writer, name, font); writer. close (); font. dispose (); xmltextreader reader = new xmltextreader (_ anyfilename); font = fontserializer. readxml (reader, name); reader. close (); assert. areequal (font. name, _ anyfont. name); assert. areequal (font. size, _ anyfont. size); assert. areequal (font. style, _ anyfont. style); font. dispose ();}
Then write the implementation code.
Using system. drawing; using system. globalization; using system. XML; namespace commonlib {public static class fontserializer {# Region Methods public static font readxml (xmlreader reader, string name) {reader. readtofollowing (name); reader. readstartelement (); string familyname = reader. readelementstring ("name"); float size = float. parse (reader. readelementstring ("size"), cultureinfo. invariantculture); bool bold = bool. parse (reader. readelementstring ("bold"); bool italic = bool. parse (reader. readelementstring ("italic"); bool strikeout = bool. parse (reader. readelementstring ("Strikeout"); bool underline = bool. parse (reader. readelementstring ("underline"); reader. readendelement (); fontstyle = fontstyle. regular; If (BOLD) fontstyle | = fontstyle. bold; If (italic) fontstyle | = fontstyle. italic; If (strikeout) fontstyle | = fontstyle. strikeout; If (underline) fontstyle | = fontstyle. underline; font = new font (familyname, size, fontstyle); Return font;} public static void writexml (xmlwriter writer, string name, Font font) {writer. writestartelement (name); writer. writeelementstring ("name", Font. name); writer. writeelementstring ("size", Font. size. tostring (cultureinfo. invariantculture); writer. writeelementstring ("bold", Font. bold. tostring (); writer. writeelementstring ("italic", Font. italic. tostring (); writer. writeelementstring ("Strikeout", Font. strikeout. tostring (); writer. writeelementstring ("underline", Font. underline. tostring (); writer. writeendelement () ;}# endregion }}
We have used stream and binaryformatter to serialize and deserialize font, But We Cannot serialize font on any node in the XML file. The above implementation can solve this problem.