Application Scenario:
Design a task scheduling system in which configuration information is stored in XML rows in a tasks.config configuration file, with more than one task in the configuration. Different tasks, there will be different configuration information and settings.
Solution 1: Read directly with XPath
Advantages: 1. Direct; 2. Flexible (configuration can be changeable)
Disadvantages: 1. Unfriendly, to write a bunch of ways to read XML data, rewrite different XML fragments each time you have a new task; 2. Error prone, most likely because you write a wrong node attribute name without getting the data
Solution 2: Use object serialization as an XML document
Disadvantages: 1. There must be a well-defined type when deserializing the configuration.
Advantages: 1. Friendly, the data in XML is deserialized directly into the object's attributes; 2. Not easy to make mistakes, why? You must first define the type serialization after use, you do not tell me that you are handwritten XML;
The problem now is to design a method to solve its shortcomings. Even if there are different configurations I can also give you deserialization. So it's not our focus to draw the same part. We are concerned with how to reproduce different configuration XML as instances. Since all objects are inherited from object, then we set the type of the extension part to object. After a test, the deserialized object is a xmlnode[] array. So what we're going to do is convert this xmlnode[] array to text, and then use the client to deserialize the text with the defined type.
Code prototypes:
[Serializable,
XmlRoot (elementname = "Configuration")]
public class Xmlconfig
{
<summary>
Extended
</summary>
[XmlElement ("extend")]
Public object Extend {get; set;}
<summary>
Get an instance of an extended type that has been set
</summary>
<typeparam name= "T" > Extended type </typeparam>
<returns> Extended class Instance </returns>
Public T getextend<t> () where T:class
{
Return serializer.xmldeserializerformtext<t> (Extendrawxml);
}
<summary>
Extend extended XML fragment
</summary>
<returns></returns>
Protected string Extendrawxml
{
Get
{
var nodes = Extend as xmlnode[];
if (nodes = null | | nodes. Length = = 0)
Return "<extend/>";
var w = new StringWriter ();
XmlWriter writer = new XmlTextWriter (w);
Writer. WriteStartElement ("extend");
foreach (var node in nodes)
Writer. WriteRaw (node. OuterXml);
Writer. WriteEndElement ();
Writer. Close ();
return w.tostring ();
}
}
}
[Serializable,
XmlRoot ("Extend")]
public class Myextend
{
public int Id {get; set;}
public string Name {get; set;}
}