XLINQ Introduction Part 3 Of 3(转与CodeProject)
来源:百度文库 编辑:神马文学网 时间:2024/06/12 21:59:39
XLINQ Introduction Part 3 Of 3
BySacha Barber.
An introduction to LINQ
C# (C# 3.0)
Windows (Vista), .NET (.NET 3.0)
Win32, VS (VS2005)
Dev
Posted: 11 May 2007
Views: 368
Note:This is an unedited reader contributionModify |Delete
Announcements
Vista API competition$10,000 in prizes
Vista Mobile comp:Win a Samsung UMPC
Vista Secure APIcomp: Win a Laptop!
Monthly Competition
Search Articles Authors Advanced Search
Sitemap
PrintBroken Article?BookmarkDiscussSend to a friend
12 votes for this article.
Popularity: 5.17. Rating: 4.79 out of 5.
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else‘s work without reference then pleaseReport this article.
Download demo application1 for .NET 2.0 (includes src code) -2,133 Kb Download demo application2 for .NET 3.0 / WPF (includes src code) - 2,618 Kb
Contents
IntroductionA Note About The Demo AppsPrerequisitesLets Get Into XLINQ ThenXLINQ ClassesCreating New XmlSaving XmlLoading XmlTraversing XmlWorking With The Root NodeAppending New ElementsUpdating Existing ElementsDeleting Existing ElementsQuerying XmlUsing XLINQ To Access 3rd Party Xml Data
Thats itConclusionHistoryBibilography
.NET 3.0 has now been released, so we should all know it by now shouldn‘t we. Jeez, doesn‘t seem like that long ago that .NET 2.0 came along. Well for those that dont realize .NET 3.0 actually contains quite a lot of new stuff, such as :
Windows Workflow Foundation (WWF) : Managing object lifecycles / persistent object storage Windows Communication Foundation (WCF) : The new communication layer Windows Presentation Foundation (WPF) : The new presenstation layer (XAML) Windows Cardspace : Which provides a standards-based solution for working with and managing diverse digital identities
So as you can see there is a lot to be learnt right there. I‘m in the process of learning WPF/WCF but I am also interested in a little gem called LINQ, that I believe will be part of .NET 3.5 and Visual Stuio "Orcas" (as its known now). LINQ will add new features to both C# and VB .NET. LINQ has 3 flavours
LINQ : Language Integrated Query for in memory objects (renamed in March 2007 Orcas CTP to LINQ to objects) DINQ : Language Integrated Query for databases (renamed in March 2007 Orcas CTP to LINQ to SQL) XLINQ : Language Integrated Query for XML (renamed in March 2007 Orcas CTP to LINQ to XML)
LINQ is pretty cool, and I have been looking into it of late, so I thought I would write an article about what I have learnt in the LINQ/DLINQ/XLINQ areas, in the hope that it may just help some of you good folk. This article will be focussed on XLINQ, and is the third in a series of 3 proposed articles.
The proposed article series content will be as follows:
Part1 : will be all about standard LINQ, which is used to query in memory data objects such as List, arrays etc etcPart2 : will be about using DLINQ, which is LINQ for database data Part3 (this article) : will be about using XLINQ, which is LINQ for XML data
Before I start bombarding people with even more information, than they can possibly handle, let me just talk briefly about the files attached to this article.
This article contains 2 seperate zip files. The zip files are the 2 demo applications.
DEMO application 1
Is based on using Visual Studio 2005 with .NET 2.0 framework, and the May 2006 LINQ CTP which is availablehere
It can be seen that the XML is syntax highlighted, this is all thanks to the free and fantastic Fireball code highlighter, available righthere at codeproject.
The main window allows the user to try out various XLINQ activites such as :
Create a new XML tree section Create a new XML document Open an existing XML document Find root node attributes Query the XML using standard LINQ query operators as described inPart1 of this series Updating XML sections Deleting XML sections
The 2nd form within this 1st demo application (available from "What About A Web Query" menu), uses XLINQ to get an RSS feed from Flickr, using a Flickr API string. You should not need to download anything extra for this to work, as it is all in the code. The Flickr RSS feed is then queried (this is what LINQ is all about, Language Intergrated Query Language, remember) using XLINQ, and the results are put into a new structure, using standard LINQ projection, and then the results are then used to populate a FlowLayoutPanel with PictureBox controls that represent the gathered images. The user is also free to change the type of Flickr search being performed, and may page through the results obtained.
DEMO application 2
Is based on using Visual Studio 2005 withThe Visual Studio Designer for WPF installed, or usingExpression BLEND and Visual Studio 2005 combination, or wordpad if you prefer to write stuff in that.
Obviously as its WPF you will also need the.NET 3.0 framework, and the May 2006 LINQ CTP which is availablehere. The idea being that those folk that want to see how WPF/XAML will work with LINQ can have a look at this project. Dont worry to much if you dont get this code, as this application will be the subject of my next article, its really being included for interest at this point, to show that LINQ and WPF can work quite nicely together actually
This is basically doing the same thing as the 2nd form of DEMO application 1, it just looks a whole lot nicer, and show cases some cool WPF stuff like:
Animations Data binding Templating Styles Resources XLINQ usage, of course
This application is not really that orientated to XLINQ, but it is something that I just wanted to try, so I thought, as i‘ve done it, why not include it here. As I say if you dont get DEMO application 2, don‘t worry, I will be going through it in another article. Its here for interest sake really.
To run the code supplied with this article you will need to install the May 2006 LINQ CTP which is availablehere, there is a new March 2007 CTP available, but its about 4GB for the full install (as its not just LINQ but the entire next generation of Visual Studio codenamed "Orcas") and quite fiddly, and probably going to change anyway, so the May 2006 LINQ CTP will be OK for the purpose of what this article is trying to demonstrate. DEMO application 1, makes use of the excellent Fireball code highlighter, available righthere at codeproject. DEMO application 2, makes use of the .NET 3.0 framework which is available for downloadhere
So what is this XLINQ stuff, well its one flavour of LINQ (Language Integrated Query) that will be part of .NET 3.5, and will certainly be part of the next verison of Visual Studio (currently called Orcas).
As a recap, recall that LINQ dealt with in memory objects such as arrays and List and Dictionary objects, whilst DLINQ or LINQ over SQL dealt with entities and database interaction. So any guesses what XLINQ is all about, well its actually XML over LINQ.
So what else can we say about this XLINQ stuff, shall we ask Microsoft what their marketing blurb is, as far as XLINQ is concerned. Well I asked them and they said this:
"XLinq was developed with Language Integrated Query over XML in mind from the beginning. It takes advantage of the Standard Query Operators and adds query extensions specific to XML. From an XML perspective XLinq provides the query and transformation power of XQuery and XPath integrated into .NET Framework languages that implement the LINQ pattern (e.g., C#, VB, etc.). This provides a consistent query experience across LINQ enabled APIs and allows you to combine XML queries and transforms with queries from other data sources. We will go in more depth on XLinq‘s query capability in section 3, "Querying XML with XLinq".
Just as significant as the Language Integrated Query capabilities of XLinq is the fact that XLinq represents a new, modernized in-memory XML Programming API. XLinq was designed to be a cleaner, modernized API, as well as fast and lightweight. XLinq uses modern language features (e.g., generics and nullable types) and diverges from the DOM programming model with a variety of innovations to simplify programming against XML. Even without Language Integrated Query capabilities XLinq represents a significant stride forward for XML programming. The next section of this document, "Programming XML", provides more detail on the in-memory XML Programming API aspect of XLinq."
Taken from XLINQ overview.doc, available at the LINQ Project [1] web site
I think that it is actually quite a good description of what XLINQ is and promises to be, Of course, it should be a good sales blurb, as XLINQ is a Microsoft invention, and it is their words after all. But what does this all mean to the average developer ?
This is something that this article will try and demonstrate, by the use of textual comments, and code snippets and real life working examples.
Unless stated otherwise the example code shown within this article will be for discussion purposes only, but dont worry I‘ve gone out of my way to actually trawl the XLINQ documentation and make a nice little demo application that contains real life working examples, of how to use XLINQ to do some of the most commonly occurring XML related tasks. So this working code is included within the DEMO application 1, and where I am specifically using the code from the DEMO application 1, I will show the following image to let you know that you can look in the code for a working example.
When you see this image, this means that I have created a worked example for you in the DEMO application 1
Obviously I have not got an example of every single thing that can be done with XLINQ, as I do have a life, not much of one, but one all the same. So I‘ll have to leave further investigation as an excercise for the reader.
The way that this article is constructed is by looking at the following items, that I would consider to be very important issues that every developer that works with xml should know.
The XLINQ class structure Creating new xml Saving xml Loading xml Traversing xml Working with the root node Appending new elements Updating existing elements Deleting existing elements Querying xml Using XLINQ to access 3rd party xml data
I‘m hoping that by going through this set of items, by the end the reader will have at least, a basic appreciation of what can be done with XLINQ and how it could be used inplace of using the DOM and XPath.
So shall we continue.
The overall XLINQ class heirachy is as shown below.
• Although XElement is low in the class hierarchy, it is the fundamental class in XLinq. XML trees are generally made up of a tree of XElements. XAttributes are name/value pairs associated with an XElement. XDocuments are created only if necessary, such as to hold a DTD or top level XML processing instruction (XProcessingInstruction). All other XNodes can only be leaf nodes under an XElement, or possibly an XDocument (if they exist at the root level).
• XAttribute and XNode are peers and not derived from a common base class (other than object). This reflects the fact that XML attributes are really name value pairs associated with an XML element not nodes in the XML tree. Contrast this with W3C DOM.
• XText is exposed in this version of XLinq, but as discussed above, it is best to think of it as a semi-hidden implementation detail except when exposing text nodes is necessary. As a user, you can get back the value of the text within an element or attribute as a string or other simple value.
• The only XNode that can have children is an XContainer, meaning either an XDocument or XElement. An XDocument can contain an XElement (the root element), an XDeclaration, an XDocumentType, or an XProcessingInstruction. An XElement can contain another XElement, an XComment, an XProcessingInstruction, and text (which can be passed in a variety of formats, but will be represented in the XML tree as text).
Taken from XLINQ overview.doc, available at the LINQ Project [1] web site
In order to undestand how XLINQ is different from existing XML document creation pratices, lets consider the following section of traditional DOM (Document Object Model) code, that creates a small xml document
Collapse
XmlDocument doc = new XmlDocument(); XmlElement name = doc.CreateElement("name"); name.InnerText = "Patrick Hines"; XmlElement phone1 = doc.CreateElement("phone"); phone1.SetAttribute("type", "home"); phone1.InnerText = "206-555-0144"; XmlElement phone2 = doc.CreateElement("phone"); phone2.SetAttribute("type", "work"); phone2.InnerText = "425-555-0145"; XmlElement street1 = doc.CreateElement("street1"); street1.InnerText = "123 Main St"; XmlElement city = doc.CreateElement("city"); city.InnerText = "Mercer Island"; XmlElement state = doc.CreateElement("state"); state.InnerText = "WA"; XmlElement postal = doc.CreateElement("postal"); postal.InnerText = "68042"; XmlElement address = doc.CreateElement("address"); address.AppendChild(street1); address.AppendChild(city); address.AppendChild(state); address.AppendChild(postal); XmlElement contact = doc.CreateElement("contact"); contact.AppendChild(name); contact.AppendChild(phone1); contact.AppendChild(phone2); contact.AppendChild(address); XmlElement contacts = doc.CreateElement("contacts"); contacts.AppendChild(contact); doc.AppendChild(contacts); Whilst this is fairly easy to do, what is not very clear is the structure that is emmitted to the actual xml document. Ok it is possible to work it out, for this trivial example, but if this were a large xml document, it would not be so clear. Shall we have a look at how XLINQ goes about doing the same job.
XElement contacts = new XElement("contacts", new XElement("contact", new XElement("name", "Patrick Hines"), new XElement("phone", "206-555-0144", new XAttribute("type", "home")), new XElement("phone", "425-555-0145", new XAttribute("type", "work")), new XElement("address", new XElement("street1", "123 Main St"), new XElement("city", "Mercer Island"), new XElement("state", "WA"), new XElement("postal", "68042") ) ) ); The first thing to say, is that it is a lot less code, and the tree structure is almost self evident from this listing, its almost as easy to read as an xml document would be. The other thing to note, is the actual syntax itself, no where do we see the methods createElement(), or AppendChild(). Instead we see new XElement which sort of makes more sense, at least in how it actually reads. Personally, I think someone who knows xml, but has not used DOM before would probably understand this new syntax a bit better, as it seems to be a closer match in term of the actual terminology used. Xml man knows of an new element as an new element, not as AppendChild(). I guess in the end, this is really down to preference.
DEMO application 1, contains 3 menus to further demonstrate this concept, look at :
Programming LINQ\Create Elements menu Programming LINQ\Create Entire Document menu Programming LINQ\Create Elements With Namespaces menu
Both XDocument and XElement expose an overloaded Save() method, the options are as follows:
XDocument.Save(string fileName)
This option simply saves the XElements content to the location specfied by the fileName parameter
XDocument.Save(System.Xml.XmlWriter writer)
This option simply saves the XElements content to an XmlWriter
XDocument.Save(TextWriter textWriter)
This option simply saves the XElements content to an TextWriter
XDocument.Save(string fileName, bool preserveWhitespace)
This option simply saves the XElements content to the location specfied by the fileName parameter, and preserves any white space
The same methods exist for XElement
Both XDocument and XElement exposes an overloaded Load() method, the options are as follows:
XDocument.Load(string uri)
This option simply loads the xml element from the location specified by the uri into a new XDocument
XDocument.Save(System.Xml.XmlReader reader)
This option simply reads the contents of an XmlReader into a new XDocument
XDocument.Save(TextReader textReader)
This option simply reads the contents of an TextReader into a new XDocument
XDocument.Save(uri fileName, bool preserveWhitespace)
This option simply read the contents of the file specfied by the fileName parameter, and preserves any white space, into a new XDocument
There is also another possibility to load xml. We can parse a string by calling the XDocument.Parse method, so lets see an example of that shall we.
XElement contacts = XElement.Parse( @" Patrick Hines 206-555-0144 425-555-0145 123 Main St Mercer Island WA 68042 10 "); One we have loaded, or parsed a string the full power of XLINQ may be used, we can traverse through nodes, inspect attributes, create new content, delete existing content.
The same methods exist for XElement
DEMO application 1, contains 2 areas to further demonstrate this concept, look at :
Programming LINQ\Opem Existing File menu (this shows the Load() method) Look at the createQuerySource() method (this shows the Parse() method)
XLinq provides methods for getting the children of an XElement. To get all of the children of an XElement (or XDocument), you can use the Nodes() method.
For example if we had the following XML
And ran the following traversal
foreach (XElement c in contacts.Nodes()) { .... } We would actually end up with the orginal XML. So how about getting to sub-elements, well its very simliar syntax infact. Lets see an example shall we.
foreach (XElement c in contacts.Elements("contact").Elements("address")) { .... }
What if we are using a XDocument, this returns IEnumerable
BySacha Barber.
An introduction to LINQ
C# (C# 3.0)
Windows (Vista), .NET (.NET 3.0)
Win32, VS (VS2005)
Dev
Posted: 11 May 2007
Views: 368
Note:This is an unedited reader contributionModify |Delete
Announcements
Vista API competition$10,000 in prizes
Vista Mobile comp:Win a Samsung UMPC
Vista Secure APIcomp: Win a Laptop!
Monthly Competition
Search Articles Authors Advanced Search
Sitemap
PrintBroken Article?BookmarkDiscussSend to a friend
12 votes for this article.
Popularity: 5.17. Rating: 4.79 out of 5.
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else‘s work without reference then pleaseReport this article.
Download demo application1 for .NET 2.0 (includes src code) -2,133 Kb Download demo application2 for .NET 3.0 / WPF (includes src code) - 2,618 Kb
Contents
IntroductionA Note About The Demo AppsPrerequisitesLets Get Into XLINQ ThenXLINQ ClassesCreating New XmlSaving XmlLoading XmlTraversing XmlWorking With The Root NodeAppending New ElementsUpdating Existing ElementsDeleting Existing ElementsQuerying XmlUsing XLINQ To Access 3rd Party Xml Data
Thats itConclusionHistoryBibilography
.NET 3.0 has now been released, so we should all know it by now shouldn‘t we. Jeez, doesn‘t seem like that long ago that .NET 2.0 came along. Well for those that dont realize .NET 3.0 actually contains quite a lot of new stuff, such as :
Windows Workflow Foundation (WWF) : Managing object lifecycles / persistent object storage Windows Communication Foundation (WCF) : The new communication layer Windows Presentation Foundation (WPF) : The new presenstation layer (XAML) Windows Cardspace : Which provides a standards-based solution for working with and managing diverse digital identities
So as you can see there is a lot to be learnt right there. I‘m in the process of learning WPF/WCF but I am also interested in a little gem called LINQ, that I believe will be part of .NET 3.5 and Visual Stuio "Orcas" (as its known now). LINQ will add new features to both C# and VB .NET. LINQ has 3 flavours
LINQ : Language Integrated Query for in memory objects (renamed in March 2007 Orcas CTP to LINQ to objects) DINQ : Language Integrated Query for databases (renamed in March 2007 Orcas CTP to LINQ to SQL) XLINQ : Language Integrated Query for XML (renamed in March 2007 Orcas CTP to LINQ to XML)
LINQ is pretty cool, and I have been looking into it of late, so I thought I would write an article about what I have learnt in the LINQ/DLINQ/XLINQ areas, in the hope that it may just help some of you good folk. This article will be focussed on XLINQ, and is the third in a series of 3 proposed articles.
The proposed article series content will be as follows:
Part1 : will be all about standard LINQ, which is used to query in memory data objects such as List, arrays etc etcPart2 : will be about using DLINQ, which is LINQ for database data Part3 (this article) : will be about using XLINQ, which is LINQ for XML data
Before I start bombarding people with even more information, than they can possibly handle, let me just talk briefly about the files attached to this article.
This article contains 2 seperate zip files. The zip files are the 2 demo applications.
DEMO application 1
Is based on using Visual Studio 2005 with .NET 2.0 framework, and the May 2006 LINQ CTP which is availablehere
It can be seen that the XML is syntax highlighted, this is all thanks to the free and fantastic Fireball code highlighter, available righthere at codeproject.
The main window allows the user to try out various XLINQ activites such as :
Create a new XML tree section Create a new XML document Open an existing XML document Find root node attributes Query the XML using standard LINQ query operators as described inPart1 of this series Updating XML sections Deleting XML sections
The 2nd form within this 1st demo application (available from "What About A Web Query" menu), uses XLINQ to get an RSS feed from Flickr, using a Flickr API string. You should not need to download anything extra for this to work, as it is all in the code. The Flickr RSS feed is then queried (this is what LINQ is all about, Language Intergrated Query Language, remember) using XLINQ, and the results are put into a new structure, using standard LINQ projection, and then the results are then used to populate a FlowLayoutPanel with PictureBox controls that represent the gathered images. The user is also free to change the type of Flickr search being performed, and may page through the results obtained.
DEMO application 2
Is based on using Visual Studio 2005 withThe Visual Studio Designer for WPF installed, or usingExpression BLEND and Visual Studio 2005 combination, or wordpad if you prefer to write stuff in that.
Obviously as its WPF you will also need the.NET 3.0 framework, and the May 2006 LINQ CTP which is availablehere. The idea being that those folk that want to see how WPF/XAML will work with LINQ can have a look at this project. Dont worry to much if you dont get this code, as this application will be the subject of my next article, its really being included for interest at this point, to show that LINQ and WPF can work quite nicely together actually
This is basically doing the same thing as the 2nd form of DEMO application 1, it just looks a whole lot nicer, and show cases some cool WPF stuff like:
Animations Data binding Templating Styles Resources XLINQ usage, of course
This application is not really that orientated to XLINQ, but it is something that I just wanted to try, so I thought, as i‘ve done it, why not include it here. As I say if you dont get DEMO application 2, don‘t worry, I will be going through it in another article. Its here for interest sake really.
To run the code supplied with this article you will need to install the May 2006 LINQ CTP which is availablehere, there is a new March 2007 CTP available, but its about 4GB for the full install (as its not just LINQ but the entire next generation of Visual Studio codenamed "Orcas") and quite fiddly, and probably going to change anyway, so the May 2006 LINQ CTP will be OK for the purpose of what this article is trying to demonstrate. DEMO application 1, makes use of the excellent Fireball code highlighter, available righthere at codeproject. DEMO application 2, makes use of the .NET 3.0 framework which is available for downloadhere
So what is this XLINQ stuff, well its one flavour of LINQ (Language Integrated Query) that will be part of .NET 3.5, and will certainly be part of the next verison of Visual Studio (currently called Orcas).
As a recap, recall that LINQ dealt with in memory objects such as arrays and List and Dictionary objects, whilst DLINQ or LINQ over SQL dealt with entities and database interaction. So any guesses what XLINQ is all about, well its actually XML over LINQ.
So what else can we say about this XLINQ stuff, shall we ask Microsoft what their marketing blurb is, as far as XLINQ is concerned. Well I asked them and they said this:
"XLinq was developed with Language Integrated Query over XML in mind from the beginning. It takes advantage of the Standard Query Operators and adds query extensions specific to XML. From an XML perspective XLinq provides the query and transformation power of XQuery and XPath integrated into .NET Framework languages that implement the LINQ pattern (e.g., C#, VB, etc.). This provides a consistent query experience across LINQ enabled APIs and allows you to combine XML queries and transforms with queries from other data sources. We will go in more depth on XLinq‘s query capability in section 3, "Querying XML with XLinq".
Just as significant as the Language Integrated Query capabilities of XLinq is the fact that XLinq represents a new, modernized in-memory XML Programming API. XLinq was designed to be a cleaner, modernized API, as well as fast and lightweight. XLinq uses modern language features (e.g., generics and nullable types) and diverges from the DOM programming model with a variety of innovations to simplify programming against XML. Even without Language Integrated Query capabilities XLinq represents a significant stride forward for XML programming. The next section of this document, "Programming XML", provides more detail on the in-memory XML Programming API aspect of XLinq."
Taken from XLINQ overview.doc, available at the LINQ Project [1] web site
I think that it is actually quite a good description of what XLINQ is and promises to be, Of course, it should be a good sales blurb, as XLINQ is a Microsoft invention, and it is their words after all. But what does this all mean to the average developer ?
This is something that this article will try and demonstrate, by the use of textual comments, and code snippets and real life working examples.
Unless stated otherwise the example code shown within this article will be for discussion purposes only, but dont worry I‘ve gone out of my way to actually trawl the XLINQ documentation and make a nice little demo application that contains real life working examples, of how to use XLINQ to do some of the most commonly occurring XML related tasks. So this working code is included within the DEMO application 1, and where I am specifically using the code from the DEMO application 1, I will show the following image to let you know that you can look in the code for a working example.
When you see this image, this means that I have created a worked example for you in the DEMO application 1
Obviously I have not got an example of every single thing that can be done with XLINQ, as I do have a life, not much of one, but one all the same. So I‘ll have to leave further investigation as an excercise for the reader.
The way that this article is constructed is by looking at the following items, that I would consider to be very important issues that every developer that works with xml should know.
The XLINQ class structure Creating new xml Saving xml Loading xml Traversing xml Working with the root node Appending new elements Updating existing elements Deleting existing elements Querying xml Using XLINQ to access 3rd party xml data
I‘m hoping that by going through this set of items, by the end the reader will have at least, a basic appreciation of what can be done with XLINQ and how it could be used inplace of using the DOM and XPath.
So shall we continue.
The overall XLINQ class heirachy is as shown below.
• Although XElement is low in the class hierarchy, it is the fundamental class in XLinq. XML trees are generally made up of a tree of XElements. XAttributes are name/value pairs associated with an XElement. XDocuments are created only if necessary, such as to hold a DTD or top level XML processing instruction (XProcessingInstruction). All other XNodes can only be leaf nodes under an XElement, or possibly an XDocument (if they exist at the root level).
• XAttribute and XNode are peers and not derived from a common base class (other than object). This reflects the fact that XML attributes are really name value pairs associated with an XML element not nodes in the XML tree. Contrast this with W3C DOM.
• XText is exposed in this version of XLinq, but as discussed above, it is best to think of it as a semi-hidden implementation detail except when exposing text nodes is necessary. As a user, you can get back the value of the text within an element or attribute as a string or other simple value.
• The only XNode that can have children is an XContainer, meaning either an XDocument or XElement. An XDocument can contain an XElement (the root element), an XDeclaration, an XDocumentType, or an XProcessingInstruction. An XElement can contain another XElement, an XComment, an XProcessingInstruction, and text (which can be passed in a variety of formats, but will be represented in the XML tree as text).
Taken from XLINQ overview.doc, available at the LINQ Project [1] web site
In order to undestand how XLINQ is different from existing XML document creation pratices, lets consider the following section of traditional DOM (Document Object Model) code, that creates a small xml document
Collapse
XmlDocument doc = new XmlDocument(); XmlElement name = doc.CreateElement("name"); name.InnerText = "Patrick Hines"; XmlElement phone1 = doc.CreateElement("phone"); phone1.SetAttribute("type", "home"); phone1.InnerText = "206-555-0144"; XmlElement phone2 = doc.CreateElement("phone"); phone2.SetAttribute("type", "work"); phone2.InnerText = "425-555-0145"; XmlElement street1 = doc.CreateElement("street1"); street1.InnerText = "123 Main St"; XmlElement city = doc.CreateElement("city"); city.InnerText = "Mercer Island"; XmlElement state = doc.CreateElement("state"); state.InnerText = "WA"; XmlElement postal = doc.CreateElement("postal"); postal.InnerText = "68042"; XmlElement address = doc.CreateElement("address"); address.AppendChild(street1); address.AppendChild(city); address.AppendChild(state); address.AppendChild(postal); XmlElement contact = doc.CreateElement("contact"); contact.AppendChild(name); contact.AppendChild(phone1); contact.AppendChild(phone2); contact.AppendChild(address); XmlElement contacts = doc.CreateElement("contacts"); contacts.AppendChild(contact); doc.AppendChild(contacts); Whilst this is fairly easy to do, what is not very clear is the structure that is emmitted to the actual xml document. Ok it is possible to work it out, for this trivial example, but if this were a large xml document, it would not be so clear. Shall we have a look at how XLINQ goes about doing the same job.
XElement contacts = new XElement("contacts", new XElement("contact", new XElement("name", "Patrick Hines"), new XElement("phone", "206-555-0144", new XAttribute("type", "home")), new XElement("phone", "425-555-0145", new XAttribute("type", "work")), new XElement("address", new XElement("street1", "123 Main St"), new XElement("city", "Mercer Island"), new XElement("state", "WA"), new XElement("postal", "68042") ) ) ); The first thing to say, is that it is a lot less code, and the tree structure is almost self evident from this listing, its almost as easy to read as an xml document would be. The other thing to note, is the actual syntax itself, no where do we see the methods createElement(), or AppendChild(). Instead we see new XElement which sort of makes more sense, at least in how it actually reads. Personally, I think someone who knows xml, but has not used DOM before would probably understand this new syntax a bit better, as it seems to be a closer match in term of the actual terminology used. Xml man knows of an new element as an new element, not as AppendChild(). I guess in the end, this is really down to preference.
DEMO application 1, contains 3 menus to further demonstrate this concept, look at :
Programming LINQ\Create Elements menu Programming LINQ\Create Entire Document menu Programming LINQ\Create Elements With Namespaces menu
Both XDocument and XElement expose an overloaded Save() method, the options are as follows:
XDocument.Save(string fileName)
This option simply saves the XElements content to the location specfied by the fileName parameter
XDocument.Save(System.Xml.XmlWriter writer)
This option simply saves the XElements content to an XmlWriter
XDocument.Save(TextWriter textWriter)
This option simply saves the XElements content to an TextWriter
XDocument.Save(string fileName, bool preserveWhitespace)
This option simply saves the XElements content to the location specfied by the fileName parameter, and preserves any white space
The same methods exist for XElement
Both XDocument and XElement exposes an overloaded Load() method, the options are as follows:
XDocument.Load(string uri)
This option simply loads the xml element from the location specified by the uri into a new XDocument
XDocument.Save(System.Xml.XmlReader reader)
This option simply reads the contents of an XmlReader into a new XDocument
XDocument.Save(TextReader textReader)
This option simply reads the contents of an TextReader into a new XDocument
XDocument.Save(uri fileName, bool preserveWhitespace)
This option simply read the contents of the file specfied by the fileName parameter, and preserves any white space, into a new XDocument
There is also another possibility to load xml. We can parse a string by calling the XDocument.Parse method, so lets see an example of that shall we.
XElement contacts = XElement.Parse( @"
The same methods exist for XElement
DEMO application 1, contains 2 areas to further demonstrate this concept, look at :
Programming LINQ\Opem Existing File menu (this shows the Load() method) Look at the createQuerySource() method (this shows the Parse() method)
XLinq provides methods for getting the children of an XElement. To get all of the children of an XElement (or XDocument), you can use the Nodes() method.
For example if we had the following XML
And ran the following traversal
foreach (XElement c in contacts.Nodes()) { .... } We would actually end up with the orginal XML. So how about getting to sub-elements, well its very simliar syntax infact. Lets see an example shall we.
foreach (XElement c in contacts.Elements("contact").Elements("address")) { .... }
What if we are using a XDocument, this returns IEnumerable
XLINQ Introduction Part 3 Of 3(转与CodeProject)
Introduction to Dependency Injection (Introduction to CAB/SCSF Part 3) ? Rich Newman
Talk at Yale: Part 3 of 3
Talk at Yale: Part 1 of 3
Talk at Yale: Part 2 of 3
Talk at Yale: Part 3 of 3 - Joel on Software
Talk at Yale: Part 2 of 3 - Joel on Software
Talk at Yale: Part 1 of 3 - Joel on Software
CodeProject: WPF: A Beginner's Guide - Part ...
Brief Introduction of Packing
Introduction of REST & RESTful WebServices
Irony - .NET Compiler Construction Kit (转与 CodeProject)
ISO7816 (part 1-3)
Taming Tiger, Part 3
Basic of Estates-part 1
java.net: Introduction to Nutch, Part 1: Crawling
java.net: Introduction to Nutch, Part 2: Searching
Volume I: History of the Talmud: Introduction
Introduction to Numerology: The Magic of Numbers
CodeProject - DrawTools(画图工具)
Part 3: Babies born drunk
Part 3 - The Linker Script
An Introduction to Software Factories (转与 architects.dzone.com)
Part 8: Bane of the Blackfeet