420 likes | 744 Views
SESSION CODE: DEV320. Simplifying XML Processing using LINQ to XML. By: Paul D. Sheriff PSheriff@pdsa.com www.pdsa.com or www.PaulSheriffInnerCircle.com. Paul.About. Paul D. Sheriff (psheriff@pdsa.com) President of PDSA, Inc. Custom Software Development, Developer Tools www.pdsa.com
E N D
SESSION CODE: DEV320 Simplifying XML Processing using LINQ to XML By: Paul D. Sheriff PSheriff@pdsa.com www.pdsa.com or www.PaulSheriffInnerCircle.com
Paul.About • Paul D. Sheriff (psheriff@pdsa.com) • President of PDSA, Inc. • Custom Software Development, Developer Tools • www.pdsa.com • eBooks (www.pdsa.com/eBooks) • Several .NET, SQL Server and SharePoint Topics • Developer Tools • .NET Productivity Framework • Paul Sheriff's Inner Circle • www.PaulSheriffInnerCircle.com
Agenda • Using the System.Xml.Linq Namespace • What is LINQ • LINQ TO XML Basics • LINQ Query Syntax • Demonstrations • A Prototyping System
Goals of this Session • Show you how to use LINQ to XML • Use anonymous types • Load a class from XML • Add/Edit/Delete XML files
System.Xml.Linq Namespace • New classes for dealing with XML • XDocument • Represents a complete, valid XML document • XElement • Represents an XML element or elements • Both provide XPath query capabilities • XPathSelectElement • XPathSelectElements
Build XML in Code • New syntax=easy creation of XML • Implicit type declaration VB.NET Dim menu = _ New XDocument( _ New XDeclaration("1.0", "utf-8", "yes"), _ New XComment("Prototype Menus"), _ New XElement("Menus")) C# var menu = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XComment("Prototype Menus"), new XElement("Menus"));
Build XML in Code (2) • Create full document VB.NET Dim menu = _ New XDocument( _ New XDeclaration("1.0", "utf-8", "yes"), _ New XComment("Prototype Menus"), _ New XElement("Menus", _ New XElement("Menu", _ New XElement("MenuID", "10"), _ New XElement("DisplayOrder", "10"), _ New XElement("MenuText", "Home") _ )))
VB.NET XML Literals • Only available in VB.NET VB.NET Dim menu = _ <Menus> <Menu> <MenuID>10</MenuID> <DisplayOrder>10</DisplayOrder> <MenuText>Home</MenuText> <Action>NextPage.aspx</Action> <ParentMenuID></ParentMenuID> </Menu> </Menus>
Loading a Document • XDocument.Load("Menus.xml") • Loads a complete valid XML Document • XElement.Load("Menus.xml") • Loads a set of XML Elements
LINQ to XML • Special LINQ syntax for dealing with XML • Simpler than using DOM • Comparable to using XPath and XQuery • Although syntax is much different • IntelliSense • In VB.NET only • When using XSD
LINQ Query Syntax • Standard “SQL-like” query syntax VB.NET From <element> in <collection> _ Where <condition> _ Order By <Expression> [Ascending | Descending] Select [<alias> = ] <column>, [<alias> = ] <column>… C# from <element> in <collection> where <condition> orderby <Expression> [ascending | descending] select <column>, <column>…
LINQ Query Syntax • Here is a sample VB.NET Dim menus = From mnu In xElem.<Menu> _ Where mnu.<ParentMenuID>.Value = "" _ Select mnu C# var menus = from mnu in xdoc.Descendants("Menu") where mnu.Element("ParentMenuID").Value == "" select mnu;
Select a Single Node • Method 1 • Load XML using XElement class • XElement.Load() • Use the XPathSelectElement method • Returns an XElement object • This is a LINQ Extension method • import/using System.Xml.XPath namespace • Method 2 • Use LINQ to XML Syntax
Select Single Node DEMO
Select Multiple Nodes • Method 1 • Use the XPathSelectElements method • LINQ Extension method • import/using System.Xml.XPath namespace • Can iterate using For Each / foreach • Method 2 • Use LINQ Query Syntax
VB XML Script • VB Allows you to script in XML Literals Dim db As New NorthwindDataContext Dim products = <Products> <%= From prod In db.Products _ Select <Product> <ProductName><%= prod.ProductName%> </ProductName> <UnitPrice><%= prod.UnitPrice %> </UnitPrice> </Product> %> </Products>
VB XML Script DEMO
Anonymous Types • Create your own custom type • Define new field names • Compiler creates new type • Sort of like an on-the-fly class • Each field is assigned a data type based on return value • You get IntelliSense on these new names
Anonymous Types DEMO
Aggregating Data • LINQ allows you to aggregate data • Sum, Min, Max, Avg, etc. • Instead of you having to loop through all the data, LINQ does it for you
Aggregating Data DEMO
Adding using LINQ • Method 1: VB.NET Only • Use XML Literal • Method 2 • Create XElement object, Populate Data • Save XML using XElement.Save method • Method 3 • Select an XElement using LINQ • Clone Element • Save XML using XElement.Save method
Updating using LINQ • Method 1 • Select element to update • XPathSelectElement • Update element • Save XML using XElement.Save method • Method 2 • Select using LINQ • Update elements • Save XML using XElement.Save method
Deleting using LINQ • Method 1 • Select element to delete • XPathSelectElement • Use the Remove method on the XElement • Save XML using XElement.Save method • Method 2 • Select using LINQ • Remove the Element • Save XML using XElement.Save method
A Prototype Application • Problem: • Want to quickly prototype application • Don’t want to setup a database • Would be nice to use XML for menu system • Solution • Create a standard prototype application • Use LINQ to XML for all menuing • Can be used on Compact Framework • LINQ to XML works (LINQ to SQL does not)
A Wrapper Class • If you want, you could wrap all these calls • Create class to do all LINQ to XML • Just use the class from the UI • Later change the class to go to database
A Wrapper Class DEMO
Summary • LINQ to XML makes processing XML easy • Full add/edit/delete • Nice Select syntax • Should simplify a lot of XML processing
Thank You • Sign up for Paul Sheriff's Inner Circle • Lifetime membership • Over $2000 worth of ebooks, video, etc. • http://www.PaulSheriffInnerCircle.com • Sign up for Framework Webcasts • http://www.pdsa.com/webcasts
Sample Code • http://www.pdsa.com/TechEd • Get Free WPF Video! • WPF Part 1: Learning basic XAML for Business Applications • ** Inner Circle Special ** • Developer Level: $150 off - $349.99 • IT Pro Level: $250 off - $749.99 • Use Code: TechEd0610 • Valid until: 07/01/10 • Over $2,000 value!
Required Slide Track PMs will supply the content for this slide, which will be inserted during the final scrub. Track Resources • Visual Studio – http://www.microsoft.com/visualstudio/en-us/ • Soma’s Blog – http://blogs.msdn.com/b/somasegar/ • MSDN Data Developer Center – http://msdn.com/data • ADO.NET Team Blog – http://blogs.msdn.com/adonet • WCF Data Services Team Blog – http://blogs.msdn.com/astoriateam • EF Design Blog – http://blogs.msdn.com/efdesign
Required Slide Resources Learning • Sessions On-Demand & Community • Microsoft Certification & Training Resources www.microsoft.com/teched www.microsoft.com/learning • Resources for IT Professionals • Resources for Developers • http://microsoft.com/technet • http://microsoft.com/msdn
Required Slide Complete an evaluation on CommNet and enter to win!
Sign up for Tech·Ed 2011 and save $500 starting June 8 – June 31st http://northamerica.msteched.com/registration You can also register at the North America 2011 kiosk located at registrationJoin us in Atlanta next year
© 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.