1 / 45

Introducing LINQ to XML

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 ).

ashley
Download Presentation

Introducing LINQ to XML

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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)

  3. 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!

  4. 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.

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

  6. 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.csproj MoreOldSchoolXml.csproj

  7. 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

  8. 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.

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

  10. 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);

  11. 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") ) );

  12. 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.

  13. 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.

  14. 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.

  15. 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 for the elements. When a namespace is included as part of an XName, it takes the following form: {http://schemas.xyxcorp.com/}localname. SimplifiedNames.csproj

  16. LINQ to XML class hierarchy AddAfterSelf, AddBeforeSelf, Remove, | Ancestors, ElementsAfterSelf, ElementsBeforeSelf, NodesAfterSelf, NodesBeforeSelf AddAnnotation Remove | Parent Add, AddFirst, RemoveNodes, ReplaceNodes | Nodes, Descendants, Element, Elements RemoveAll, RemoveAttributes, SetElementValue, SetAttributeValue| Attributes, AncestorsAndSelf, DescendantAndSelf | Load, Parse, Save, WriteTo Load, Parse, Save, WriteTo

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

  18. Loading & parsing XML LINQ 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

  19. 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.

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

  21. // imperative XElement 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);

  22. 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())

  23. 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")));

  24. 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

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

  26. 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") ) );

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

  28. 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"))) );

  29. <?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>

  30. 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!")) );

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

  32. Adding content public void Add(object content) public void Add(params object[] content) (AddFirst, AddAfterSelf, AddBeforeSelf) // IEnumerable XElement existingBooks = XElement.Load("existingBooks.xml"); XElement books = new XElement("books"); books.Add(existingBooks.Elements("book"));

  33. Removing content books.Element("book").Remove(); // remove the first book ~ books.Elements("book").Remove(); // remove all books books.SetElementValue("book", null); // ~ books.Element("book").Element("author").Value = String.Empty;

  34. Updating content XElement 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

  35. 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

  36. Working with attributes public 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();

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

  38. LINQ to XML axis methods // traverse vertically Element Attribute Elements Descendants DescendantNodes DescendantsAndSelf Ancestors AncestorNodes AncestorsAndSelf

  39. // traverse horizontally ElementsAfterSelf NodesAfterSelf ElementsBeforeSelf NodesBeforeSelf AxisMethods.csproj

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

  41. http://www.wherestheanykey.co.uk

  42. Building objects from XML Our goal is to create a collection of objects that contain the data within an XML document using the capabilities offered by LINQ to XML. BuildingObjectsFromXML.csproj

  43. Creating XML with data from a database Our 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

  44. Transforming text files into XML We 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

  45. See y’all next time!

More Related