XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ...

XML files (with LINQ)

Transcript of XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ...

XML files (with LINQ)

Introduction to LINQ (Language Integrated Query )

C#’s new LINQ capabilities allow you to write query expressions that retrieve information from many data sources, not just databases.

foreach (var number in myArray) The implicitly typed local-variable feature is one of several new C#

features that support LINQ.

LINQ to Objects can be used to filter arrays and Lists, selecting elements that satisfy a set of conditions

Repetition statements that filter arrays focus on the steps required to get the results. This is called imperative programming.

LINQ queries, however, specify the conditions that selected elements must satisfy. This is known as declarative programming.

The System.Linq namespace contains the LINQ to Objects provider.

Using LINQ with arraysLet’s look at an example: LINQWithSimpleTypeArray

// values greater than 4

var filtered = from value in values

where value > 4

select value;

var sorted = from value in values

orderby value

select value;

var sorted = from value in filtered

orderby value descending

select value;

A LINQ query begins with a from clause, which specifies a range variable (value) and the data source to query (values).If the condition in the where clause evaluates to true, the element is selected.

The select clause determines what value appears in the results.

The orderby clause sorts the query results in ascending order.

The descending modifier in the orderby clause sorts the results in descending order.

Using LINQ with arrays of objectsEmployee class (Employee.cs)LINQWithArrayOfObjects.cs

Let’s fill the empty one ourselves together

var nameSorted =

from e in employees

orderby e.LastName, e.FirstName

select e;

if (nameSorted.Any())

Console.WriteLine(nameSorted.First().ToString() + "\n");


Console.WriteLine("not found\n");

The query result’s Any method returns true if there is at least one element, and false if there are no elements.

The query result’s First method (line 45) returns the first element in the result

An orderby clause can sort the results according to multiple properties, specified in a comma-separated list.

Using LINQ with arrays of objects

Display( lastNames.Distinct(),

"Unique employee last names");

// use LINQ to select first and last names

var names =

from e in employees

select new { e.FirstName, Last = e.LastName };

The Distinct method removes duplicate elements, causing all elements in the result to be unique.

The select clause can create a new object of anonymous type (a type with no name), which the compiler generates for you based on the properties listed in the curly braces ({}).

Using LINQ with List<T>List<T> is a generic list and its members are as follows:

Method / Property Description

Add Adds an object to the end of the List.

Capacity Property that gets and sets the number of elements for which space is currently reserved in the List.

Clear Removes all elements from the List.

Contains Determines whether an element is in the List.

Count Read-only property that gets the number of elements stored in the List.

IndexOf Returns the zero-based index of the first occurrence of a value in the List

Insert Inserts an element into the List at the specified index.

Remove Removes the first occurrence of a specific object from the List.

RemoveAt Removes the element at the specified index of the List.

Sort Sorts the List.

Using LINQ with List’sLINQWithListCollection.cs

var startsWithR = from item in items let uppercaseString = item.ToUpper() where uppercaseString.StartsWith("R") orderby uppercaseString select uppercaseString;

LINQ’s let clause can be used to create a new range variable to store a temporary result for use later in the LINQ query.

IntroductionThe .NET Framework uses XML extensively.Configuration files use XML format.


XML is also used heavily in serialization.LINQ to XML provides a way to manipulate data in

XML documents using the same LINQ syntax you can use on arrays, collections, and databases.

LINQ to XML also provides a set of classes for easily navigating and creating XML documents in your code.

XML files On successfully parsing a document, some XML parsers store document

data as trees in memory. Figure below illustrates the tree structure for the document article.xml.

XML files DOMThis hierarchical tree structure is called a Document Object

Model (DOM) tree, and an XML parser that creates such a tree is known as a DOM parser.

Each element name is represented by a node.A node that contains other nodes (called child nodes or

children) is called a parent node.A parent node can have many children, but a child node can

have only one parent node.Nodes that have the same parent are called sibling nodes.A node’s descendant nodes include its children, its children’s

children and so on.A node’s ancestor nodes include its parent, its parent’s parent

and so on.The DOM tree has a single root node, which contains all the

other nodes in the document.Classes for creating, reading and manipulating XML documents

are located in the System.Xml namespace.

Reading XML files

• Namespace System.Xml.Linq contains the classes used to manipulate a DOM in .NET, referred to collectively as LINQ to XML.

• The XElement class represents a DOM element node—an XML document is represented by a tree of XElement objects.

• The XDocument class represents an entire XML document.Example: XDocumentTestForm.cs to read article.xml

Reading XML filesXDocument’s static Load method takes an XML document’s

filename and returns an XDocument containing a tree representation of the XML file.

The XDocument ’s Root property returns an XElement representing the root element of the XML file.

Because full element names consist of namespace prefix and name parts, tag and attribute names are stored as objects of class XName.

The Name property of an XElement returns an XName object containing the tag name and namespaceThe unqualified name is stored in the XName’s LocalName property.

The HasElements property can be used to test whether an elements has any child elements.

The Elements method is used to obtain an element’s children.An element’s text can be obtained using the Value property. If used on an element with children, the Value property returns all

of the text contained within its descendants, with the tags removed.

Writing to XML files

You can add content (elements, attributes, comments, processing instructions, text) to an existing XML tree.

Add child content to an XElement or an XDocument:XDocument.Add and XDocument.AddFirst

Add content as sibling nodes of an XNodeXDocument.AddAfterSelf and XDocument.AddBeforeSelf

Then XDocument.Save writes to the file.

Modifying Elements, Attributes, and Nodes in an XML TreeRemoving Elements, Attributes, and Nodes from an XML Tree

LINQ to XML Class Hierarchy

Navigate the XML document

Example: XMLFileTreeView solution

LINQ to XML Class HierarchyThe XDocument’s Elements method can return all child elements,

or only elements with a given tag name.The Elements method is actually defined in the XContainer

class, the base class of XDocument and XElement.The Descendants method returns all descendant elements with the

given tag name, not just direct children.The Element method, a member of the XContainer class,

returns the first child element with the given tag name or null if no such element exists.

The Attribute method of the XElement class returns an XAttribute object matching the given attribute name or null if no such object exists.

The XAttribute class represents an XML attribute—it holds the attribute’s name and value.

LINQ to XML Class Hierarchy XObject class is an abstract base class for all nodes and attributes.

The NodeType property returns a value of the XmlNodeType enumeration . The Parent property of XObject, which returns the parent of the given XObject or null if the parent does not exist.

The Document property (defined in XObject) retrieves the XDocument representing the document root.

The XNode class is a common abstract base class of all the node types in an XML document. The PreviousNode of XNode returns the previous sibling, or null if there is none. NextNode returns the next sibling node in the tree, or null if there is none. The ToString methods of all subclasses of XNode return the XML they and

their children (if any) represent with proper indentation. The Nodes method of XContainer returns a reference to an object of type IEnumerable<XNode> containing all children of the given XContainer.

XText holds the contents of a text node. Its Value property returns the contained text.

Comments are represented by the XComment class.

More to learnhttp://msdn.microsoft.com/en-us/library/bb387098.aspx