How can I serialize a string from XML into a class property of type Regex?
Here’s the elements in the XML file:
<IncludeRegex><![CDATA[#include\\s*\\\"\\s*(?<FileName>.+\\\\*\\.*.+)\\s*\\\"]]></IncludeRegex>
<IncludeDefineRegex><![CDATA[#define\s*[A-Za-z_0-9]+\s*\""\s*(?<FileName>.+\.[a-zA-Z0-9]+)\s*\""]]></IncludeDefineRegex>
In my class, that I serialize, I have these properties:
public Regex IncludeRegex { get; set; }
public Regex IncludeDefineRegex { get; set; }
The rest of the class serializes without a problem, but the Regex properties fail to serialize. One option is to have alternate properties:
public string IncludeRegex { get; set; }
public string IncludeDefineRegex { get; set; }
[XmlIgnore]
public Regex IncludeRegexActual { get; private set; }
[XmlIgnore]
public Regex IncludeDefineRegexActual { get; private set; }
And set these properties in the setters of IncludeRegex and IncludeDefineRegex or an init function. This works, but can I do it without the duplicate properties?
I don’t think you can do that with regular XML serialization, you have to implement IXmlSerializable to control the serialization directly.