Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

45
Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner

Transcript of Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Page 1: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Introducing LINQ to XMLFlorin−Tudor Cristea, Microsoft Student Partner

Page 2: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

XmlDocument,and XmlNode, and XmlElement! Oh, my!You cursed brat! Look what you've done! I'm melting! melting! Oh, what a world! What a world! (Wicked Witch of the West)

Page 3: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

XML is ubiquitous nowadays, and is used extensively in applications written using general-purpose languages such as C#. It is used to exchange data between applications, store configuration information, persist temporary data, generate web pages or reports, and perform many other things. It is everywhere!

Page 4: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Until now, XML hasn’t been natively supported by most programming languages, which therefore required the use of APIs to deal with XML data. These APIs include XmlDocument, XmlReader, XPathNavigator, XslTransform for XSLT, and SAX and XQuery implementations.

Page 5: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

<books> <book title="Windows Forms in Action"> <publisher>Manning</publisher> </book> <book title="RSS and Atom in Action"> <publisher>Manning</publisher> </book></books>

Page 6: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

The problem is that these APIs are not well integrated with programming languages, often requiring several lines of unnecessarily convoluted code to achieve a simple result.

OldSchoolXml.csprojMoreOldSchoolXml.csproj

Page 7: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Whereas the DOM is low-level and requires a lot of code to precisely formulate what we want to achieve, LINQ to XML provides a higher-level syntax that allows us to do simple things simply.

HelloLinqToXml.csproj

Page 8: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

As you can see, LINQ to XML is more visual than the DOM. The structure of the code to get our XML fragment is close to the document we want to produce itself. Microsoft names this approach the Functional Construction pattern.

Page 9: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

<books> <book> <title>LINQ in Action</title> <author>Fabrice Marguerie </author> <author>Steve Eichert</author> <author>Jim Wooley</author> <publisher>Manning</publisher> </book></books>

Page 10: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

XmlDocument doc = new XmlDocument();XmlElement books = doc.CreateElement("books");XmlElement author1 = doc.CreateElement("author");author1.InnerText = "Fabrice Marguerie";XmlElement author2 = doc.CreateElement("author");author2.InnerText = "Steve Eichert";XmlElement author3 = doc.CreateElement("author");author3.InnerText = "Jim Wooley";XmlElement title = doc.CreateElement("title");title.InnerText = "LINQ in Action";XmlElement book = doc.CreateElement("book");book.AppendChild(author1);book.AppendChild(author2); book.AppendChild(author3);book.AppendChild(title);books.AppendChild(book);doc.AppendChild(books);

Page 11: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

new XElement("books", new XElement("book", new XElement("author", "Fabrice Marguerie"), new XElement("author", "Steve Eichert"), new XElement("author", "Jim Wooley"), new XElement("title", "LINQ in Action"), new XElement("publisher", "Manning") ));

Page 12: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Functional construction allows a complete XML tree to be created in a single statement. Rather than imperatively building up our XML document by creating a series of temporary variables for each node, we build XML in a functional manner, which allows the XML to be built in a way that closely resembles the resulting XML.

Page 13: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Context-free XML creation. When creating XML using the DOM, everything must be done within the context of a parent document. This document-centric approach to creating XML results in code that is hard to read, write, and debug. Within LINQ to XML, elements and attributes have been granted first-class status. They’re standalone values that can be created outside the context of a document or parent element.

Page 14: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Simplified names. One of the most confusing aspects of XML is all the XML names, XML namespaces, and namespace prefixes. When creating elements with the DOM, developers have several overloaded factory methods that allow them to include details of the fully expanded name of an element. How the DOM figures out the name, namespace, and prefix is confusing and complicates the API unnecessarily. Within LINQ to XML, XML names have been greatly simplified.

Page 15: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Rather than having to worry about local names, qualified names, namespaces, and namespace prefixes, we can focus on a single fully expanded name. The XName class represents a fully expanded name, which includes the namespace and local name forthe elements. When a namespace is included as part of an XName, it takes the following form: {http://schemas.xyxcorp.com/}localname.SimplifiedNames.csproj

Page 16: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

LINQ to XML class hierarchy

AddAnnotation

AddAfterSelf, AddBeforeSelf, Remove, | Ancestors, ElementsAfterSelf, ElementsBeforeSelf,

NodesAfterSelf, NodesBeforeSelf

Add, AddFirst, RemoveNodes,

ReplaceNodes | Nodes, Descendants, Element,

Elements

RemoveAll, RemoveAttributes, SetElementValue,

SetAttributeValue| Attributes, AncestorsAndSelf,

DescendantAndSelf | Load, Parse, Save, WriteTo

Remove | Parent

Load, Parse, Save, WriteTo

Page 17: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Working with XML using LINQ“Any fool can use a computer. Many do.” (Ted Nelson)

Page 18: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Loading & parsing XMLLINQ to XML allows XML to be loaded from a variety of input sources. These sources include a file, a URL, and an XmlReader. To load XML, the static Load method on XElement can be used.

When loading XML from a file or URL, LINQ to XML uses the XmlReader class.

LoadingXML.csproj

Page 19: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

If you’re interested in accessing the XML declarations (XDeclaration), top-level XML processing instructions (XProcessingInstruction), XML document type definitions (XDocumentType), or XML comments (XComment) within an XML document, you’ll need to load your XML into an XDocument object instead of an XElement.

Page 20: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Creating XML// functionalXElement books = new XElement("books", new XElement("book", new XElement("author", "Don Box"), new XElement("title", "Essential .NET") ));

Page 21: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

// imperativeXElement book = new XElement("book");book.Add(new XElement("author", "Don Box"));book.Add(new XElement("title", "Essential .NET"));XElement books = new XElement("books");books.Add(book);

Page 22: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

public XElement(XName name)public XElement(XName name, object content)public XElement(XName name, params object[] content)

content → string, XText, XElement, XAttribute, XProcessingInstruction, XComment, IEnumerable, null, object (.ToString())

Page 23: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

XElement books = new XElement("books", new XElement("book", new XElement("title", "LINQ in Action"), new XElement("authors", new XElement("author", "Fabrice Marguerie"), new XElement("author", "Steve Eichert"), new XElement("author", "Jim Wooley")), new XElement("publicationDate", "January 2008")), new XElement("book", new XElement("title", "Ajax in Action"), new XElement("authors", new XElement("author", "Dave Crane"), new XElement("author", "Eric Pascarello"), new XElement("author", "Darren James")), new XElement("publicationDate", "October 2005")));

Page 24: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

If you need to include namespace prefixes in your XML, you’ll have to alter your code to explicitly associate a prefix with an XML namespace. To associate a prefix with a namespace, you can add an XAttribute object to the element requiring the prefix and append the prefix to the XNamespace.Xmlns namespace.

CreatingXML.csproj

Page 25: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Creating XML DocumentsWhen working with XElement objects, we allow XElement objects, XAttribute objects, XText, IEnumerable, and strings to be addedas content. XDocument allows the following to be added as child content: XDocumentType (1, DTD), XDeclaration (1), XProcessingInstruction (n), XElement (1, root), XComment (n).

Page 26: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

XDocument doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XProcessingInstruction("XML-stylesheet", "friendly-rss.xsl"), new XElement("rss", new XElement("channel", "my channel") ));

Page 27: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

<?XML-stylesheet friendly-rss.xsl?><rss> <channel>my channel</channel></rss>

Page 28: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

XDocument d = new XDocument( new XProcessingInstruction("XML-stylesheet", "href='http://iqueryable.com/friendly-rss.xsl' type='text/xsl' media='screen'"), new XElement("rss", new XAttribute("version", "2.0"), new XElement("channel", new XElement("item", "my item"))) );

Page 29: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

<?XML-stylesheet href='http://iqueryable.com/friendly-rss.xsl' type='text/xsl' media='screen'?><rss version="2.0"> <channel> <item>my item</item> </channel></rss>

Page 30: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

XDocument html = new XDocument( new XDocumentType("HTML", "-//W3C//DTD HTML 4.01//EN", "http://www.w3.org/TR/html4/strict.dtd", null), new XElement("html", new XElement("body", "This is the body!")) );

Page 31: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <body>This is the body!</body></html>

Page 32: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Adding contentpublic void Add(object content)public void Add(params object[] content) (AddFirst, AddAfterSelf, AddBeforeSelf)

// IEnumerableXElement existingBooks = XElement.Load("existingBooks.xml");XElement books = new XElement("books");books.Add(existingBooks.Elements("book"));

Page 33: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Removing contentbooks.Element("book").Remove(); // remove the first book ~books.Elements("book").Remove(); // remove all booksbooks.SetElementValue("book", null); // ~

books.Element("book").Element("author").Value = String.Empty;

Page 34: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Updating contentXElement books = new XElement("books.xml");books.Element("book").SetElementValue("author", "Bill Gates"); // simple content

books.Element("book").Element("author").ReplaceNodes(new XElement("foo")); // advanced content

Page 35: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

books.Element("book").ReplaceNodes( new XElement("title", "Ajax in Action"), new XElement("author", "Dave Crane")); // entire contents

var titles = books.Descendants("title").ToList();foreach(XElement title in titles) { title.ReplaceWith(new XElement("book_title", (string) title));} // entire node

Page 36: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Working with attributespublic XAttribute(XName name, object value)

new XElement("book", new XAttribute("pubDate", "July 31, 2006"));book.Add(new XAttribute("pubDate", "July 31, 2006"));book.SetAttributeValue("pubDate", "October 1, 2006");book.Attribute("pubDate").Remove();

Page 37: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Saving XMLbooks.Save(@"c:\books.xml");

Page 38: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

LINQ to XML axis methods// traverse verticallyElementAttributeElementsDescendantsDescendantNodesDescendantsAndSelfAncestorsAncestorNodesAncestorsAndSelf

Page 39: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

// traverse horizontallyElementsAfterSelfNodesAfterSelf ElementsBeforeSelfNodesBeforeSelf

AxisMethods.csproj

Page 40: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Common LINQ to XML scenarios“C++ : where friends have access to your private members.” (Gavin Russell Baker)

Page 41: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

http://www.wherestheanykey.co.uk

Page 42: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Building objects from XMLOur goal is to create a collection of objects that contain the data within an XML document using the capabilities offered byLINQ to XML.

BuildingObjectsFromXML.csproj

Page 43: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Creating XML with data from a databaseOur goal is to export XML of the books within our book catalog database. This will allow us to share our catalog with other LinqBooks users.

CreatingXMLWithDatabaseData.csproj

Page 44: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

Transforming text files into XMLWe aim to transform a text file into a hierarchical XML document. The text file will contain the following book information: the ISBN, title, author(s), publisher, publication date, and price.

FlatFileToXML.csproj

Page 45: Introducing LINQ to XML Florin−Tudor Cristea, Microsoft Student Partner.

See y’all next time!