XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ capabilities allow you to write query expressions that retrieve.

Slides:



Advertisements
Similar presentations
XML-XSL Introduction SHIJU RAJAN SHIJU RAJAN Outline Brief Overview Brief Overview What is XML? What is XML? Well Formed XML Well Formed XML Tag Name.
Advertisements

XML: Extensible Markup Language
LINQ and Collections An introduction to LINQ and Collections.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
1 XSLT – eXtensible Stylesheet Language Transformations Modified Slides from Dr. Sagiv.
RDF Tutorial.
Introduction to XLink Transparency No. 1 XML Information Set W3C Recommendation 24 October 2001 (1stEdition) 4 February 2004 (2ndEdition) Cheng-Chia Chen.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
XML –Query Languages, Extracting from Relational Databases ADVANCED DATABASES Khawaja Mohiuddin Assistant Professor Department of Computer Sciences Bahria.
September 15, 2003Houssam Haitof1 XSL Transformation Houssam Haitof.
A tour of new features introducing LINQ. Agenda of LINQ Presentation We have features for every step of the way LINQ Fundamentals Anonymous Functions/Lambda.
Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.
JSP Standard Tag Library
 Introduction  What is LINQ  Syntax  How to Query  Example Program.
Databases and LINQ Visual Basic 2010 How to Program 1.
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
XP New Perspectives on XML Tutorial 6 1 TUTORIAL 6 XSLT Tutorial – Carey ISBN
XP 1 CREATING AN XML DOCUMENT. XP 2 INTRODUCING XML XML stands for Extensible Markup Language. A markup language specifies the structure and content of.
WORKING WITH XSLT AND XPATH
XP New Perspectives on XML, 2 nd Edition Tutorial 10 1 WORKING WITH THE DOCUMENT OBJECT MODEL TUTORIAL 10.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Session IV Chapter 9 – XML Schemas
LINQ TO XML Mike Taulty Developer & Platform Group Microsoft UK
Working with the XML Document Object Model ©NIITeXtensible Markup Language/Lesson 7/Slide 1 of 44 Objectives In this lesson, you will learn to: *Identify.
XML DOM Functionality in.NET DSK Chakravarthy
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
ECA 228 Internet/Intranet Design I XSLT Example. ECA 228 Internet/Intranet Design I 2 CSS Limitations cannot modify content cannot insert additional text.
CITA 330 Section 6 XSLT. Transforming XML Documents to XHTML Documents XSLT is an XML dialect which is declared under namespace "
XSLT Kanda Runapongsa Dept. of Computer Engineering Khon Kaen University.
McGraw-Hill/Irwin © 2004 by The McGraw-Hill Companies, Inc. All rights reserved. Scripting with the DOM Ellen Pearlman Eileen Mullin Programming the Web.
Neal Stublen How does XMLReader work?  XmlReader.Read() Advances to next node XmlReader properties access node name, value, attributes,
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Database Systems Part VII: XML Querying Software School of Hunan University
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 17 – Flag Quiz Application Introducing One-Dimensional.
 Although VERY commonly used, arrays have limited capabilities  A List is similar to an array but provides additional functionality, such as dynamic.
Introduction to LINQ Chapter 11. Introduction Large amounts of data are often stored in a database—an organized collection of data. A database management.
CSCI 3327 Visual Basic Chapter 13: Databases and LINQ UTPA – Fall 2011.
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
Introduction to the Document Object Model Eugenia Fernandez IUPUI.
Object Oriented Programming Generic Collections and LINQ Dr. Mike Spann
 defined as Extensible Markup Language (XML) is a set of rules for encoding documents  Defines structure and data.
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and Collections UTPA – Fall 2011.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
Trees Chapter 10. CS 308 2Chapter Trees Preview: Preview: The data organizations presented in previous chapters are linear, in that items are one.
DOM (Document Object Model) - Parsing and Reading HTML and XML -
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises 1 Xiang Lian The University of Texas – Pan American Edinburg,
XPath --XML Path Language Motivation of XPath Data Model and Data Types Node Types Location Steps Functions XPath 2.0 Additional Functionality and its.
XSLT: How Do We Use It? Nancy Hallberg Nikki Massaro Kauffman.
LINQ to DATABASE-2.  Creating the BooksDataContext  The code combines data from the three tables in the Books database and displays the relationships.
LINQ Language Integrated Query LINQ1. LINQ: Why and what? Problem Many data sources: Relational databases, XML, in-memory data structures, objects, etc.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
XML DOM Week 11 Web site:
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
XML Schema – XSLT Week 8 Web site:
1 XSL Transformations (XSLT). 2 XSLT XSLT is a language for transforming XML documents into XHTML documents or to other XML documents. XSLT uses XPath.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Programming Web Pages with JavaScript
Parsing XML XDocument and LINQ
Introduction to LINQ and Generic Collections
Introduction to the Document Object Model
Visual Basic 2010 How to Program
Week 11 Web site: XML DOM Week 11 Web site:
Processing XML.
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
More Sample XML By Sadia Anjum.
Introduction to LINQ Chapter 11.
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections UTPA – Fall 2012 This set of slides is revised from lecture slides.
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises UTPA – Fall 2012 This set of slides is revised from lecture.
Presentation transcript:

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 arrays Let’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 objects Employee 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"); else 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 List is a generic list and its members are as follows: Method / PropertyDescription 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 ’s LINQWithListCollection.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.

Introduction The.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 DOM This 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 files XDocument ’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 namespace The 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:XElementXDocument XDocument.Add and XDocument.AddFirst Add content as sibling nodes of an XNodeXNode XDocument.AddAfterSelf and XDocument.AddBeforeSelf Then XDocument.Save writes to the file. Modifying Elements, Attributes, and Nodes in an XML Tree Removing Elements, Attributes, and Nodes from an XML Tree

LINQ to XML Class Hierarchy

Navigate the XML document Example: XMLFileTreeView solution

LINQ to XML Class Hierarchy The 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 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 learn