Reading XML Attributes using LINQ to XML in Silverlight


We are building a Website in Silverlight that needs to access some data from a XML file.

Here is an example of XML document.


<?xml version="1.0" encoding="utf-8" ?>

<Contents>
  <
Content Title="Mahesh Chand"
         
ImageUri="ADO.NET Programming with C#"
         
RedirectText="APress"
         
RedirectUri="2003"
         
Description="44.95" > 
 
</
Content> 

  <Content Title="Raj Beniwal"
         
ImageUri="Mastering Silverlight"
         
RedirectText="Mindcracker"
         
RedirectUri="2010"
         
Description="49.95" />

  <Content Title="Mike Gold"
         
ImageUri="Visual C# Programming"
         
RedirectText="Microgold Press"
         
RedirectUri="2005"
         
Description="44.95" /> 

</Contents>

 

Before you can use LINQ to XML, you must add a reference to the System.Xml.Linq.dll assembly and import the following namespace in the code.

using System.Xml.Linq;

 

The following code snippet loads XML file in a Silverlight application using LINQ to XML and reads all of the attributes of the nodes.  To run this code, create a Silverlight Web application, add a Button and a ListBox control and write the following code on the Button click event handler.

// Load XML document
XDocument
doc = XDocument.Load("Authors.xml");

// Get all nodes of the root node

IEnumerable<XNode> nodes =
    from xmlNode in doc.Root.Nodes()
    select xmlNode;

        

foreach (XNode node in nodes)
{          

    XElement elm = (XElement)node;

    IEnumerable<XAttribute> attList =
    from at in elm.Attributes()
    select at;

    foreach (XAttribute att in attList)
    {

        listBox1.Items.Add(att.Name + " : " + att.Value);
    }

}

         

 


Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.