简体   繁体   中英

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 duplicate 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM