Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Part 6: Developing for the Web > Chapter 13: XML in Modern Programming

A.13. Chapter 13: XML in Modern Programming


Create XML documents.

XML documents can be built easily with the XElement and XAttribute classes. XElement represents an element, and its constructor accepts as arguments the element's name and either the element's value or a series of attributes and nested elements. XAttribute represents an attribute, and its constructor accepts as arguments the attribute's name and its value. You can also assign an XML document directly to an XElement.


Master It

Create the XML segment that describes an object of the Item type, defined by the following class:

Class Item
     Property ID As String
     Property Name As String
     Property Prices As Price
     Property Name As String
Class Price
          Property Retail As PriceDetails
          Property WholeSale As PriceDetails
          Class PriceDetails
               Property Price As Decimal
               Property VolumeDiscount As Decimal
End Class
Class Dimension
     Property Width As Decimal

Property Height As Decimal
     Property Depth As Decimal
End Class


Solution

The first technique is called functional construction, and you build the XML document by appending XElements and XAttributes to a variable:

Dim prod = New XElement("Item", New XAttribute("ID", "A001"),
           New XElement("Name", "ProductName"),
           New XElement("Price",
               New XElement("Retail",
                            New XAttribute("Price", "10.95"),
                            New XAttribute("VolumeDiscount", "0.25")),
               New XElement("WholeSale",
                            New XAttribute("Price", "8.50"),
                            New XAttribute("VolumeDiscount", "0.20"))))

Alternatively, you can declare a variable and set it to the equivalent XML document (which is the same document that the expression prod.ToString will return):

Dim prod = <Item ID="A001">
                <Name>ProductName</Name>
                <Price>
                    <Retail Price="10.95" VolumeDiscount="0.25"/>
                    <WholeSale Price="8.50" VolumeDiscount="0.20"/>
                </Price>
           </Item>


Navigate through an XML document and locate the information you need.

The XElement class provides a number of methods for accessing the contents of an XML document. The Elements method returns the child elements of the current element by the name specified with the argument you pass to the method as a string. The Element method is quite similar, but it returns the first child element by the specified name. The Descendants method returns all the elements by the specified name under the current element, regardless of whether they're direct children of the current element. Finally, the Attribute method returns the value of the attribute by the specified name of the current element.


Master It

Assuming an XML document with the following structure, write the expressions to retrieve all cities in the document and all cities under the third country in the document.

<Countries>
   <Country>
      <City> ... </City>
      <City> ... </City>
   </Country>
   <Country>
   ...
   </Country>
   ...
</Countries>


Solution

The following expression returns all cities in the document:

Dim cities =
countries.Elements("Country").Elements("Cities").Elements("City")

The cities variable is an IEnumerable collection of XElement objects. Likewise, to retrieve the cities of the third country, you must retrieve the Elements collection of the third element:

Dim countryCities =
countries.Elements("Country")(2).Elements("Cities").Elements("City")


Master It

Assuming that both country and city names are specified in the document with the Name element, explain the difference between the queries:

Dim q1 = countries.Elements("Country").Elements("Name")
Dim q2 = countries.Descendants("Name")


Solution

The first query returns all country names in the document, because the Elements method retrieves all elements that are directly under the element to which it's applied (not their children's children, even if the same element name is repeated). The second query returns all country and city names, because the Descendants method retrieves all elements by the specified name under the element to which it's applied (regardless of their nesting).


Convert arbitrary objects into XML documents and back with serialization.

Serialization is the process of converting an object into a stream of bytes. This process (affectionately known as dehydration) generates a stream of bytes or characters, which can be stored or transported. To serialize an object, you can use the BinaryFormatter or SoapFormatter class. You can also use the XmlSerializer class to convert objects into XML documents. All three classes expose a Serialize class that accepts as arguments the object to be serialized and a stream object and writes the serialized version of the object to the specified stream. The opposite of serialization is called deserialization. To reconstruct the original object, you use the Deserialize method of the same class you used to serialize the object.


Master It

Describe the process of serializing an object with the XmlSerializer class.


Solution

First create a Stream object to accept the result of serialization; this stream is usually associated with a file:

Dim saveFile As New FileStream("Objects.xml", FileMode.Create)

Then create an instance of the XmlSerializer class, passing to its construction the type of object you want to serialize:

Dim serializer As New XmlSerializer(custom_type)

And finally call the serializer object's Serialize method, passing as an argument the object you want to serialize:

serializer.Serialize(stream, object)


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial