How to serialize a regular expression type using .NET XML serialization
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 dupli开发者_如何转开发cate properties?
I don't think you can do that with regular XML serialization, you have to implement IXmlSerializable to control the serialization directly.
The problem is, that Regex cannot be serialized. That can be solved by implementing IXmlSerializable
. As you cannot change the Regex
class, you have to handle it in another class. You might be able to do something like this (untested, out of my head):
public class MyRegEx : Regex, IXmlSerializable {...}
Now you have to implement the interface and have to use that class instead of Regex.
精彩评论