Simplifying XML Processing using LINQ to XML By: Paul D. Sheriff [email protected] www.pdsa.com or www.PaulSheriffInnerCircle.com SESSION CODE: DEV320
Simplifying XML Processing using LINQ to XMLBy: Paul D. [email protected] or www.PaulSheriffInnerCircle.com
SESSION CODE: DEV320
Paul.AboutPaul D. Sheriff ([email protected])
President of PDSA, Inc.Custom Software Development, Developer Tools
www.pdsa.comeBooks (www.pdsa.com/eBooks)
Several .NET, SQL Server and SharePoint TopicsDeveloper Tools
.NET Productivity FrameworkPaul Sheriff's Inner Circle
www.PaulSheriffInnerCircle.com
AgendaUsing the System.Xml.Linq NamespaceWhat is LINQLINQ TO XML BasicsLINQ Query SyntaxDemonstrationsA Prototyping System
Goals of this SessionShow you how to use LINQ to XMLUse anonymous typesLoad a class from XMLAdd/Edit/Delete XML files
System.Xml.Linq NamespaceNew classes for dealing with XMLXDocument
Represents a complete, valid XML documentXElement
Represents an XML element or elementsBoth provide XPath query capabilities
XPathSelectElementXPathSelectElements
Build XML in CodeNew syntax=easy creation of XMLImplicit type declarationVB.NETDim 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.NETDim 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 LiteralsOnly available in VB.NETVB.NET Dim menu = _ <Menus> <Menu> <MenuID>10</MenuID> <DisplayOrder>10</DisplayOrder> <MenuText>Home</MenuText> <Action>NextPage.aspx</Action> <ParentMenuID></ParentMenuID> </Menu> </Menus>
Loading a DocumentXDocument.Load("Menus.xml")
Loads a complete valid XML DocumentXElement.Load("Menus.xml")
Loads a set of XML Elements
Build XML / Load Document
DEMO
LINQ to XMLSpecial LINQ syntax for dealing with XMLSimpler than using DOMComparable to using XPath and XQuery
Although syntax is much differentIntelliSense
In VB.NET onlyWhen using XSD
LINQ Query SyntaxStandard “SQL-like” query syntaxVB.NETFrom <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 SyntaxHere is a sample
VB.NETDim 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 NodeMethod 1
Load XML using XElement classXElement.Load()
Use the XPathSelectElement methodReturns an XElement object
This is a LINQ Extension methodimport/using System.Xml.XPath namespace
Method 2Use LINQ to XML Syntax
Select Single Node
DEMO
Select Multiple NodesMethod 1
Use the XPathSelectElements methodLINQ Extension method
import/using System.Xml.XPath namespaceCan iterate using For Each / foreach
Method 2Use LINQ Query Syntax
Select Multiple Nodes
DEMO
VB XML ScriptVB Allows you to script in XML LiteralsDim 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 TypesCreate your own custom typeDefine new field namesCompiler creates new type
Sort of like an on-the-fly classEach field is assigned a data type based on return value
You get IntelliSense on these new names
Anonymous Types
DEMO
Aggregating DataLINQ 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 LINQMethod 1: VB.NET Only
Use XML LiteralMethod 2
Create XElement object, Populate DataSave XML using XElement.Save method
Method 3Select an XElement using LINQClone ElementSave XML using XElement.Save method
Updating using LINQMethod 1
Select element to updateXPathSelectElement
Update elementSave XML using XElement.Save method
Method 2Select using LINQUpdate elementsSave XML using XElement.Save method
Deleting using LINQMethod 1
Select element to deleteXPathSelectElement
Use the Remove method on the XElementSave XML using XElement.Save method
Method 2Select using LINQRemove the ElementSave XML using XElement.Save method
Add/Edit/Delete using LINQ
DEMO
A Prototype ApplicationProblem:
Want to quickly prototype applicationDon’t want to setup a databaseWould be nice to use XML for menu system
SolutionCreate a standard prototype applicationUse LINQ to XML for all menuing
Can be used on Compact FrameworkLINQ to XML works (LINQ to SQL does not)
A Prototype Application
DEMO
A Wrapper ClassIf you want, you could wrap all these callsCreate class to do all LINQ to XMLJust use the class from the UILater change the class to go to database
A Wrapper Class
DEMO
SummaryLINQ to XML makes processing XML easyFull add/edit/deleteNice Select syntaxShould simplify a lot of XML processing
Thank YouSign up for Paul Sheriff's Inner Circle
Lifetime membershipOver $2000 worth of ebooks, video, etc.http://www.PaulSheriffInnerCircle.com
Sign up for Framework Webcastshttp://www.pdsa.com/webcasts
Sample Codehttp://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.99IT Pro Level: $250 off - $749.99Use Code: TechEd0610Valid until: 07/01/10Over $2,000 value!
Track ResourcesVisual 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
Resources
www.microsoft.com/techedSessions On-Demand & Community Microsoft Certification & Training Resources
Resources for IT Professionals Resources for Developers
www.microsoft.com/learning
http://microsoft.com/technet http://microsoft.com/msdn
Learning
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.
JUNE 7-10, 2010 | NEW ORLEANS, LA