January 26, 2021
Hot Topics:

Programming with LINQ to XML for Objects (LINQ to XSD)

  • By Paul Kimmel
  • Send Email »
  • More Articles »

Defining the XML Schema

An XML Schema document (XSD) describes how a well-formed XML document matching this schema will be formed. The XSD document in Listing 2 indicates that documents conforming to this schema will contain a complex type named Zoos. The complex type Zoos will contain 0 to many complex types called Zoo. Zoo elements contain a Name, City, State, and Country; these are all string types.

Listing 2: An XSD document that describes what the contents of XML document that conform to this schema will contain.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
   <xs:element name="Zoos">
            <xs:element ref="Zoo" minOccurs="0"

   <xs:element name="Zoo">
            <xs:element name="Name"    type="xs:string"/>
            <xs:element name="City"    type="xs:string"/>
            <xs:element name="State"   type="xs:string"/>
            <xs:element name="Country" type="xs:string"/>

For all intents and purposes, the XSD document (named ZooSchema.xsd) in Listing 2 describes XML documents that will contain data representing a collection of Zoo data. For the XML document to be considered well-formed, it can be expected to contain the elements described by the associated schema.

Code Generating the Wrapper Classes

XML and XSD documents have been around a while. What's new is that, by associating the Microsoft.Xml.Schema.Linq.dll assembly with the project and changing the Build Action for the schema document, you can instruct Visual Studio .NET to use the LINQ to XSD technology to code generate wrapper classes. Here is the extra step needed:

  1. In the C# Class Library project, select the ZooSchema.xsd.
  2. Press F4 to display the Properties Window.
  3. Change the Build Action to LinqToXsdSchema (see Figure 1).
  4. Figure 1: Associate a build action with the XSD file.

  5. Build the C# Class Library project.

After you build the class library project, press F2 to open the Object Explorer. The Object Browser will contain information about the class library, including a namespace to match the namespace defined in the XSD document and classes representing the code generated elements. For your purposes, you are interested in the Zoos and Zoo classes (see Figure 2).

Click here for a larger image.

Figure 2: The code generated elements, generated by the new LINQ to XSD technology.

At this point, you can reference the GeneratedCode class library, import the namespaces, and use Zoos and Zoo like any other class. The LINQ to XSD technology will get the data from the XML document and populate a collection that you can query with LINQ.

Page 2 of 3

This article was originally published on June 20, 2008

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date