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

Chapter 24. Applying LINQ > LINQ TO XML FUNCTIONAL CONSTRUCTORS

24.7. LINQ TO XML FUNCTIONAL CONSTRUCTORS

As shown in previous chapters, one of the themes in C# is easier construction of objects, with features such as object initializers and anonymous types. LINQ to XML continues this theme by introducing a new, easier way to create XML documents called functional construction in which the constructor calls can be nested in a way that naturally reflects the structure of the XML document. In the following Try It Out, you use functional constructors to make a simple XML document containing customers and orders.

TRY IT OUT: LINQ to XML Constructors

Follow these steps to create the example in Visual Studio 2010:

  1. Create a new console application called BegVCSharp_24_3_LinqToXmlConstructors in the directory C:\BegVCSharp\Chapter24.

  2. Open the main source file Program.cs.

  3. Add a reference to the System.Xml.Linq namespace to the beginning of Program.cs as shown here:

    using System;
    using System.Collections.Generic;
    using System.Linq;using System.Xml.Linq;using System.Text;

  4. Add the following code to the Main() method in Program.cs:



    static void Main(string[] args)
    {
    
                XDocument xdoc = new XDocument(
                new XElement("customers",
                new XElement("customer",
                new XAttribute("ID", "A"),
                new XAttribute("City", "New York"),
                new XAttribute("Region", "North America"),
                new XElement("order",
                new XAttribute("Item", "Widget"),
                new XAttribute("Price", 100)
                ),
                new XElement("order",
                new XAttribute("Item", "Tire"),
                new XAttribute("Price", 200)
                )
                ),
                new XElement("customer",
                new XAttribute("ID", "B"),
                new XAttribute("City", "Mumbai"),
                new XAttribute("Region", "Asia"),
                new XElement("order",
                new XAttribute("Item", "Oven"),
                new XAttribute("Price", 501)
                )
                )
                )
                );
                Console.WriteLine(xdoc);
    
                Console.Write("Program finished, press Enter/Return to continue:");
                Console.ReadLine();}
    
    					  

    Code snippet BegVCSharp\Chapter24\BegVCSharp243 LinqToXmlConstructors\Program.cs
    
    					  

  5. Compile and execute the program (you can just press F5 for Start Debugging). You will see the output shown here:

    <customers>
      <customer ID="A" City="New York" Region="North America">
        <order Item="Widget" Price="100" />
        <order Item="Tire" Price="200" />
      </customer>

    <customer ID="B" City="Mumbai" Region="Asia">
        <order Item="Oven" Price="501" />
      </customer>
    </customers>
    Program finished, press Enter/Return to continue:

The XML document shown on the output screen contains a very simplified version of the customer/order data you have seen in previous examples. Note that the root element of the XML document is <customers>, which contains two nested <customer> elements. These in turn contain a number of nested <order> elements. The <customer> elements have two attributes, <City> and <Region>, and the <order> elements have <Item> and <Price> attributes.

Press Enter/Return to exit the program and make the console screen disappear. If you used Ctrl+F5 (Start Without Debugging), you may need to press Enter/Return twice.

How It Works

The first step is to reference the System.Xml.Linq namespace. All of the following examples in this chapter require that you add this line to your program:

using System.Xml.Linq;

While the System.Linq namespace is included by default when you create a project, the System.Xml.Linq namespace is not included; you must add this line explicitly.

Next are the calls to the LINQ to XML constructors XDocument(), XElement(), and XAttribute(), which are nested inside one another as shown here:

XDocument xdoc = new XDocument(
                new XElement("customers",
                    new XElement("customer",
                        new XAttribute("ID", "A"),
                        .

Note that the code here looks like the XML itself, where the document contains elements, and each element contains attributes and other elements. Let's look at each of these constructors in turn:

  • XDocument(): The highest-level object in the LINQ to XML constructor hierarchy is XDocument(), which represents the complete XML document. It appears in your code here:

    static void Main(string[] args)
    {
                XDocument xdoc = new XDocument(
    .
                );

    The parameter list for XDocument() is omitted in the previous code fragment so you can see where the XDocument() call begins and ends. Like all the LINQ to XML constructors, XDocument() takes an array of objects (object[]) as one of its parameters so that a number of other objects created by other constructors can be passed to it. All the other constructors you call in this program are parameters in the one call to the XDocument() constructor. The first (and only) parameter you pass in this program is the XElement() constructor.

  • XElement(): An XML document must have a root element, so in most cases the parameter list of XDocument() will begin with an XElement object. The XElement() constructor takes the name of the element as a string, followed by a list of the XML objects contained within that element. Here, the root element is "customers", which in turn contains a list of "customer" elements:

    new XElement("customers",
                        new XElement("customer",
    .
                        ),
    .
                    )

    The "customer" element does not contain any other XML elements. Instead, it contains three XML attributes, which are constructed with the XAttribute() constructor.

  • XAttribute(): Here you add three XML attributes to the "customer" element, named "ID", "City", and "Region":

    new XAttribute("ID", "A"),
                            new XAttribute("City", "New York"),
                            new XAttribute("Region", "North America"),

    Because an XML attribute is by definition a leaf XML node containing no other XML nodes, the XAttribute() constructor takes only the name of the attribute and its value as parameters. In this case, the three attributes generated are ID="A", City="New York", and Region="North America".

  • Other LINQ to XML constructors: While you do not call them in this program, there are other LINQ to XML constructors for all the XML node types, such as XDeclaration() for the XML declaration at the start of an XML document, XComment() for an XML comment, and so on. These other constructors are not used often but are available if you need them for precise control over formatting an XML document.

Finishing up the explanation of the first example, you add two child "order" elements to the "customer" element following the "ID", "City" and "Region" attributes:

new XElement("order",
                            new XAttribute("Item", "Widget"),
                            new XAttribute("Price", 100)
                        ),
                        new XElement("order",
                            new XAttribute("Item", "Tire"),
                            new XAttribute("Price", 200)
                        )

These order elements have "Item" and "Price" attributes but no other children.

Next, you display the contents of the XDocument to the console screen:

Console.WriteLine(xdoc);

This prints out the text of the XML document using the default ToString() method of XDocument().

Finally, you pause the screen so you can see the console output, and then wait until the user presses Enter:

Console.Write("Program finished, press Enter/Return to continue:");
            Console.ReadLine();

After that your program exits the Main() method, which ends the program.



  

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