Your SlideShare is downloading. ×
Introduction to LINQ To XML
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Introduction to LINQ To XML

2,631
views

Published on

Slides from an an internal SBTI talk about LINQ to XML

Slides from an an internal SBTI talk about LINQ to XML

Published in: Technology, News & Politics

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
2,631
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
87
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • Talk about demo of purchase orders over $40.00
  • Talk about the anonymous type we will be creating.
  • Item Count
  • Item Count
  • Transcript

    • 1. Monthly Features: Technical Showcase
      What is LINQ to XML?
      Microsoft says:
      “LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. LINQ to XML uses the latest .NET Framework language capabilities and is comparable to an updated, redesigned Document Object Model (DOM) XML programming interface.”
    • 2. Monthly Features: Technical Showcase
      What is LINQ to XML?
      Alternative to using XPath
      Uses anonymous types to provide strongly typed access to XML elements and attributes.
      Not a replacement for XSLT
    • 3. Monthly Features: Technical Showcase
      Sample XML File
      <?xmlversion="1.0"encoding="utf-8" ?>
      <PurchaseOrders>
        <PurchaseOrderId="83123"Total="59.97">
          <CustomerName>Joe Bob</CustomerName>
          <CustomerState>TX</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Blue"Price="19.99" />
            <ItemId="32324"Name="T-Shirt"Color="White"Price="9.99" />
            <ItemId="01283"Name="Jeans"Color="Blue"Price="29.99" />
          </Items>
        </PurchaseOrder>
        <PurchaseOrderId="83124"Total="19.99">
          <CustomerName>Bob Joe</CustomerName>
          <CustomerState>TX</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Red"Price="19.99" />
          </Items>
        </PurchaseOrder>
        <PurchaseOrderId="83125"Total="49.98">
          <CustomerName>John Smith</CustomerName>
          <CustomerState>OK</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Blue"Price="19.99" />
            <ItemId="01283"Name="Jeans"Color="Blue"Price="29.99" />
          </Items>
        </PurchaseOrder>
      </PurchaseOrders>
    • 4. Monthly Features: Technical Showcase
      Get PurchaseIds of orders greater than $40.00
      Returns
      XDocumentpurchaseOrderXml = XDocument.Load("PurchaseOrder.xml");
       
      varpurchaseIds = frompurchaseOrderinpurchaseOrderXml.Root.Elements("PurchaseOrder")
                        wherefloat.Parse(purchaseOrder.Attribute("Total").Value) > 40.00f
                        selectpurchaseOrder.Attribute("Id").Value;
       
      foreach (varpurchaseIdinpurchaseIds)
        Console.WriteLine("PurchaseId: {0}", purchaseId);
      Order Ids Greater than $40.00
      PurchaseId: 83123
      PurchaseId: 83125
    • 5. Monthly Features: Technical Showcase
      Add a reference to System.Xml.Linq.
      Classes
      XDocument– Class used to interact with an XML document
      XElement– Represents an element in an XML document
      XAttribute– Represents an attribute in an XML document
      XNamespace – Used to specify a namespace in an XML document
      i.e.: /my:myFields/my:RepeatingTable
      LINQ to XML Classes
    • 6. Monthly Features: Technical Showcase
      Methods and Properties
      XDocument.Root– Returns the root XElement of the XML document
      XContainer.Elements() – Returns an IEnumberable<XElement> of all matching elements
      Example: myDocument.Root.Elements(“PurchaseOrders”);
      XContainer.Attributes() – Returns an IEnumerable<XAttribute>
      XContainer.Element() – Returns a single XElement
      Example: purchaseOrderElement.Element(“CustomerName”).Value;
      XContainer.Attribute() – Returns a single XAttribute
      .Any() Extension Method – Returns true if items exist in a IEnumerable<>
      .First() Extension Method – Returns first item in an IEnumberable<>
      LINQ to XML Methods and Properties
    • 7. Monthly Features: Technical Showcase
      Sample XML File
      <?xmlversion="1.0"encoding="utf-8" ?>
      <PurchaseOrders>
        <PurchaseOrderId="83123"Total="59.97">
          <CustomerName>Joe Bob</CustomerName>
          <CustomerState>TX</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Blue"Price="19.99" />
            <ItemId="32324"Name="T-Shirt"Color="White"Price="9.99" />
            <ItemId="01283"Name="Jeans"Color="Blue"Price="29.99" />
          </Items>
        </PurchaseOrder>
        <PurchaseOrderId="83124"Total="19.99">
          <CustomerName>Bob Joe</CustomerName>
          <CustomerState>TX</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Red"Price="19.99" />
          </Items>
        </PurchaseOrder>
        <PurchaseOrderId="83125"Total="49.98">
          <CustomerName>John Smith</CustomerName>
          <CustomerState>OK</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Blue"Price="19.99" />
            <ItemId="01283"Name="Jeans"Color="Blue"Price="29.99" />
          </Items>
        </PurchaseOrder>
      </PurchaseOrders>
    • 8. Monthly Features: Technical Showcase
      Get Purchase Orders greater than $40.00
      Returns
      XDocumentpurchaseOrderXml = XDocument.Load("PurchaseOrder.xml");
       
      varpurchaseOrders = frompurchaseOrderinpurchaseOrderXml.Root.Elements("PurchaseOrder")
                           wherefloat.Parse(purchaseOrder.Attribute("Total").Value) > 40.00f
                           selectnew
                           {
                             Id = purchaseOrder.Attribute("Id").Value,
                             Total = float.Parse(purchaseOrder.Attribute("Total").Value),
                             CustomerName = purchaseOrder.Element("CustomerName").Value,
                             CustomerState = purchaseOrder.Element("CustomerState").Value
                           };
       
      foreach (varpurchaseOrderinpurchaseOrders)
        Console.WriteLine("PurchaseId: {0}: {1} ({2}) - {3}",
            purchaseOrder.Id,
            purchaseOrder.CustomerName,
            purchaseOrder.CustomerState,
            purchaseOrder.Total);
      Returns
      Orders Greater than $40.00
      PurchaseId: 83123: Joe Bob (TX) - 59.97
      PurchaseId: 83125: John Smith (OK) - 49.98
    • 9. Monthly Features: Technical Showcase
      Sample XML File
      <?xmlversion="1.0"encoding="utf-8" ?>
      <PurchaseOrders>
        <PurchaseOrderId="83123"Total="59.97">
          <CustomerName>Joe Bob</CustomerName>
          <CustomerState>TX</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Blue"Price="19.99" />
            <ItemId="32324"Name="T-Shirt"Color="White"Price="9.99" />
            <ItemId="01283"Name="Jeans"Color="Blue"Price="29.99" />
          </Items>
        </PurchaseOrder>
        <PurchaseOrderId="83124"Total="19.99">
          <CustomerName>Bob Joe</CustomerName>
          <CustomerState>TX</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Red"Price="19.99" />
          </Items>
        </PurchaseOrder>
        <PurchaseOrderId="83125"Total="49.98">
          <CustomerName>John Smith</CustomerName>
          <CustomerState>OK</CustomerState>
          <Items>
            <ItemId="26134"Name="Polo Shirt"Color="Blue"Price="19.99" />
            <ItemId="01283"Name="Jeans"Color="Blue"Price="29.99" />
          </Items>
        </PurchaseOrder>
      </PurchaseOrders>
    • 10. Monthly Features: Technical Showcase
      Get Purchase Orders with at least 2 items
      Returns
      XDocumentpurchaseOrderXml = XDocument.Load("PurchaseOrder.xml");
       
      varpurchaseOrders = frompurchaseOrderinpurchaseOrderXml.Root.Elements("PurchaseOrder")
                           wherepurchaseOrder.Element("Items").Elements("Item").Count() >= 2
                           selectnew
                           {
                               Id = purchaseOrder.Attribute("Id").Value,
                               ItemCount = purchaseOrder.Element("Items").Elements("Item").Count()
                           };
       
      foreach (varpurchaseOrderinpurchaseOrders)
          Console.WriteLine("PurchaseId: {0}: ItemCount: {1}",
              purchaseOrder.Id,
              purchaseOrder.ItemCount);
      Returns
      Orders With at least 2 items
      PurchaseId: 83123: ItemCount: 3
      PurchaseId: 83125: ItemCount: 2
    • 11. Monthly Features: Technical Showcase
      InfoPath
      <my:myFieldsxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-12-30T15:48:37"
                   xmlns:xd="http://schemas.microsoft.com/office/infopath/2003"xml:lang="en-US">
        <my:RepeatingTable>
          <my:Item>
            <my:Name>Polo Shirt</my:Name>
            <my:Color>Red</my:Color>
            <my:Price>19.99</my:Price>
          </my:Item>
          <my:Item>
            <my:Name>Jeans</my:Name>
            <my:Color>Blue</my:Color>
            <my:Price>29.99</my:Price>
          </my:Item>
        </my:RepeatingTable>
        <my:Id>83123</my:Id>
      </my:myFields>
    • 12. Monthly Features: Technical Showcase
      Querying a repeating table in InfoPath
      Reference System.Linq (contained in System.Core)
      Reference System.Xml.Linq (contained in System.Xml.Linq)
      Returns
      // use the MainDataSource to read the XML of the InfoPath Form
      XDocumentinfoPathDocument = XDocument.Load(newSystem.IO.StringReader(MainDataSource.CreateNavigator().OuterXml));
       
      // required to access my: namespace
      XNamespacemyNamespace = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-12-30T15:48:37";
       
      // use descendants node to find any element with the name Item in the tree
      var items = from item ininfoPathDocument.Descendants(myNamespace + "Item")
                  selectnew
                  {
                      Name = item.Element(myNamespace + "Name").Value,
                      Color = item.Element(myNamespace + “Color").Value,
                      Price = item.Element(myNamespace + "Price").Value
                  };
       
      foreach (var item in items)
      {
          // do something
      }
    • 13. Monthly Features: Technical Showcase
      Questions?
      Code Samples available at www.dotnetmafia.com.