Introducing Microsoft .NET (Pro-Developer)

The solution to the problem of needing easier access to XML documents than that provided by generic parsers, as for every compatibility problem in computing, is to add a layer of abstraction. (The solution to every performance problem in computing is to remove a layer of abstraction, but I digress.) Since the operation of reading and writing XML documents is highly repetitive, it makes sense to provide prefabricated functionality that performs the repetitive operations and frees programmers to think about their business logic.

The .NET Framework provides this capability through a class called System.Xml.Serialization.XmlSerializer. An object of this class knows how to take any .NET object, read its public properties and member variables, and write them into an XML document. This process is known as serialization, and I like to think of it as dehydrating an object and storing the resulting powder. The same serializer can then take the XML document at a later time, read its contents, and re-create an object of the same class having the same values as the original object. This process is known as deserialization, and I think of it as adding water to rehydrate the object. Figure 7-2 shows a conceptual diagram of the process. The first example in this chapter illustrates this technique.

.NET abstracts away the details of XML documents by making them .NET objects.

Figure 7-2: The .NET XML serialization process.

It often happens that the structure of the XML documents that our programs need to deal with is not under our control. Rather than accepting the default output of .NET serialization, we need to control that output to make our dehydrated object layout conform to an XML schema that someone else wrote, perhaps someone who wasn’t using .NET or anything else from Microsoft and never intends to. The XML serialization features of .NET let us control the structure of the documents that our objects produce when serialized, thereby allowing us to produce any type of XML document that we require. The second example in this chapter illustrates this technique.

We can control serialization output so as to match other people’s XML layout if necessary.

We need the control over our XML serialization to be fast and easy, and .NET provides us with this capability as well. Instead of having to manually write our .NET classes to match an XML schema, we can use a tool to generate them for us. The third example in this chapter illustrates this technique.

An SDK tool makes the control process easy.

Finally, .NET provides us with a full-featured generic XML parser for those times when we have to operate at a low level of abstraction. The fourth example in this chapter demonstrates this.

.NET comes with a full- fledged generic XML parser.

Категории