New book: MCTS Self-Paced Training Kit (Exam 70-516): Accessing Data with Microsoft .NET Framework 4

627390.inddWe’re happy to report that MCTS Self-Paced Training Kit (Exam 70-516): Accessing Data with Microsoft .NET Framework 4, by Glenn Johnson, is now available to purchase (672 pages, Print ISBN 978-0-7356-2739-0).

Maximize your performance on the exam by mastering the skills and experience measured by these objectives:

      • Modeling data
      • Managing connections and context
      • Querying data
      • Manipulating data
      • Developing and deploying reliable applications

Assess your skills with the practice tests on CD. You can work through hundreds of questions using multiple testing modes to meet your specific learning needs. You get detailed explanations for right and wrong answers—including a customized learning path that describes how and where to focus your studies.

Please view the table of contents from this previous post.

Please enjoy this excerpt from Chapter 5, “LINQ to XML”.

C H A P T E R 5


XML has been a rapidly growing technology because it provides a verbose means for
transferring data that can be understood easily by computers as well as by people. You
will often need to query the XML data.

Another common requirement is to transform XML into a different format. In some scenarios,
you simply want to convert XML to a different form of XML. In other scenarios, you
might want to convert XML into HTML. You might even want to convert XML into text.

This chapter’s first lesson shows how you can use XmlDocument and XmlReader classes
to query XML data. Lesson 2, “Querying with LINQ to XML,” shows how you can use LINQ
to XML to retrieve data from XML. Lesson 3, “Transforming XML Using LINQ to XML,” uses
LINQ to XML to transform XML data.

Exam objectives in this chapter:

■ Query XML.

Lessons in this chapter:

■ Lesson 1: Working with the XmlDocument and XmlReader Classes
■ Lesson 2: Querying with LINQ to XML
■ Lesson 3 Transforming XML Using LINQ to XML

Before You Begin
You must have some understanding of Microsoft C# or Visual Basic 2010, and you should
be familiar with XPath query language, also known as XML Path Language. XPath is an XML
technology that was created to provide a common syntax and semantics to address parts of
an XML document. XPath has been a W3C (World Wide Web Consortium,
recommendation since November 1999.

XPath uses a path notation for navigating through the hierarchical structure of an XML
document that is similar to that used for navigating the folder hierarchy on your disk drive
when you locate a file. Just as you can locate a file by specifying a relative or explicit path, you
can locate parts of an XML document by supplying a relative or explicit path. Even the asterisk
(*) is useful as the “all” wildcard when locating parts of an XML document. This chapter
exposes you to simple XPath queries, but XPath is not the chapter’s focus.

This chapter requires only the hardware and software listed at the beginning of this book.



Lesson 1: Working with the XmlDocument and XmlReader Classes

The XmlDocument and XmlReader classes have existed since Microsoft .NET Framework 1.0. This lesson explores each of these classes, showing benefits and drawbacks of using each in your code.


The XmlDocument Class

The W3C has provided standards that define the structure and a standard programming interface called the Document Object Model (DOM) that can be used in a wide variety of environments and applications for XML documents. Classes that support the DOM typically are capable of random access navigation and modification of the XML document.

The XML classes are accessible by setting a reference to the System.Xml.dll file and adding the Imports System.Xml (C# using System.Xml;) directive to the code.

The XmlDocument class is an in-memory representation of XML using the DOM Level 1 and Level 2. This class can be used to navigate and edit the XML nodes.

There is another class, XmlDataDocument, which inherits from the XmlDocument class and represents relational data. The XmlDataDocument class, in the System.Data.dll assembly, can expose its data as a data set to provide relational and nonrelational views of the data. This lesson focuses on the XmlDocument class.

These classes provide many methods to implement the Level 2 specification and contain methods to facilitate common operations. The methods are summarized in Table 5-1. The XmlDocument class, which inherits from XmlNode, contains all the methods for creating XML elements and XML attributes.




Creating the XmlDocument Object


To create an XmlDocument object, start by instantiating an XmlDocument class. The XmlDocument object contains CreateElement and CreateAttribute methods that add nodes to the XmlDocument object. The XmlElement contains the Attributes property, which is an XmlAttributeCollection type. The XmlAttributeCollection type inherits from the XmlNamedNodeMap class, which is a collection of names with corresponding values.
The following code shows how an XmlDocument class can be created from the beginning and saved to a file. Note that import System.Xml (C# using System.Xml;) and Import System.IO (C# using System.IO;) was added to the top of the code file.

Sample of Visual Basic Code
Private Sub CreateAndSaveXmlDocumentToolStripMenuItem_Click( _
      ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles CreateAndSaveXmlDocumentToolStripMenuItem.Click
   ‘Declare and create new XmlDocument
   Dim xmlDoc As New XmlDocument()

   Dim el As XmlElement
   Dim childCounter As Integer
   Dim grandChildCounter As Integer

     ‘Create the xml declaration first
   xmlDoc.AppendChild( _
     xmlDoc.CreateXmlDeclaration(“1.0”, “utf-8”, Nothing))

     ‘Create the root node and append into doc
     el = xmlDoc.CreateElement(“MyRoot”)

   ‘Child Loop
   For childCounter = 1 To 4
     Dim childelmt As XmlElement
     Dim childattr As XmlAttribute

     ‘Create child with ID attribute
     childelmt = xmlDoc.CreateElement(“MyChild”)
     childattr = xmlDoc.CreateAttribute(“ID”)
     childattr.Value = childCounter.ToString()

     ‘Append element into the root element
     For grandChildCounter = 1 To 3
       ‘Create grandchildren

   ‘Save to file

   txtLog.AppendText(“XmlDocumentTest.xml Created” + vbCrLf)

End Sub

Private Function getFilePath(ByVal fileName As String) As String
   Return Path.Combine(Environment.GetFolderPath( _
     Environment.SpecialFolder.Desktop), fileName)
End Function


Sample of C# Code
private void createAndSaveXmlDocumentToolStripMenuItem_Click(
object sender, EventArgs e)
   //Declare and create new XmlDocument
   var xmlDoc = new XmlDocument();

   XmlElement el;
   int childCounter;
   int grandChildCounter;

   //Create the xml declaration first
     xmlDoc.CreateXmlDeclaration(“1.0”, “utf-8”, null));

   //Create the root node and append into doc
   el = xmlDoc.CreateElement(“MyRoot”);


   //Child Loop
   for (childCounter = 1; childCounter <= 4; childCounter++)
     XmlElement childelmt;
     XmlAttribute childattr;

     //Create child with ID attribute
     childelmt = xmlDoc.CreateElement(“MyChild”);
     childattr = xmlDoc.CreateAttribute(“ID”);
     childattr.Value = childCounter.ToString();

     //Append element into the root element
     for (grandChildCounter = 1; grandChildCounter <= 3;

        //Create grandchildren

   //Save to file
   txtLog.AppendText(“XmlDocumentTest.xml Created\r\n”);

private string getFilePath(string fileName)
   return Path.Combine(Environment.GetFolderPath(
     Environment.SpecialFolder.Desktop), fileName);


This code started by creating an instance of XmlDocument. Next, the XML declaration is created and placed inside the child collection. An exception is thrown if this is not the first child of XmlDocument. After that, the root element is created and the child nodes with corresponding attributes are created. Finally, a call is made to the getFilePath helper method to assemble a file path to save the file to your desktop. This helper method will be used in subsequent code samples. The following is the XML file that was produced by running the code sample:

XML File
<?xml version=”1.0″ encoding=”utf-8″?>
   <MyChild ID=”1″>
      <MyGrandChild />
     <MyGrandChild />
     <MyGrandChild />
   <MyChild ID=”2″>
     <MyGrandChild />
     <MyGrandChild />
     <MyGrandChild />
   <MyChild ID=”3″>
     <MyGrandChild />
     <MyGrandChild />
     <MyGrandChild />
   <MyChild ID=”4″>
     <MyGrandChild />
     <MyGrandChild />
     <MyGrandChild />


PRACTICE Work with the XmlDocument and XmlReader Classes

In this practice, you analyze an XML file, called Orders.xml, which contains order information. Your first objective is to write a program that can provide the total price of all orders.
You also need to provide the total and the average freight cost, per order. Here is an example of what the file looks like.

Orders.xml File
<Orders> <Order OrderNumber=”SO43659″>
<LineItem Line=”1″ PID=”349″ Qty=”1″ Price=”2024.9940″ Freight=”50.6249″ />
<LineItem Line=”2″ PID=”350″ Qty=”3″ Price=”2024.9940″ Freight=”151.8746″ />
<LineItem Line=”3″ PID=”351″ Qty=”1″ Price=”2024.9940″ Freight=”50.6249″ />
<LineItem Line=”4″ PID=”344″ Qty=”1″ Price=”2039.9940″ Freight=”50.9999″ />
<LineItem Line=”5″ PID=”345″ Qty=”1″ Price=”2039.9940″ Freight=”50.9999″ />
<LineItem Line=”6″ PID=”346″ Qty=”2″ Price=”2039.9940″ Freight=”101.9997″ />
<LineItem Line=”7″ PID=”347″ Qty=”1″ Price=”2039.9940″ Freight=”50.9999″ />
<LineItem Line=”8″ PID=”229″ Qty=”3″ Price=”28.8404″ Freight=”2.1630″ />
<LineItem Line=”9″ PID=”235″ Qty=”1″ Price=”28.8404″ Freight=”0.7210″ />
<LineItem Line=”10″ PID=”218″ Qty=”6″ Price=”5.7000″ Freight=”0.8550″ />
<LineItem Line=”11″ PID=”223″ Qty=”2″ Price=”5.1865″ Freight=”0.2593″ />
<LineItem Line=”12″ PID=”220″ Qty=”4″ Price=”20.1865″ Freight=”2.0187″ />
<Order OrderNumber=”SO43660″>
<LineItem Line=”1″ PID=”326″ Qty=”1″ Price=”419.4589″ Freight=”10.4865″ />
<LineItem Line=”2″ PID=”319″ Qty=”1″ Price=”874.7940″ Freight=”21.8699″ />
<!–Many more orders here –>


Your second objective is to determine whether it’s faster to use XmlDocument or XmlReader to retrieve this data, because you need to process many of these files every day, and performance is critical.

This practice is intended to focus on the features that have been defined in this lesson, so a Console Application project will be implemented. The first exercise implements the solution based on XmlDocument, whereas the second exercise implements the solution based on XmlReader.

If you encounter a problem finishing an exercise, the completed projects can be installed from the Code folder on the companion CD.

Comments (1)

  1. george says:

    Friends dont miss it please

    esp. USA,UK and German friends