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" ?>

Content Title="Mahesh Chand"
ImageUri="ADO.NET Programming with C#"
Description="44.95" > 

  <Content Title="Raj Beniwal"
ImageUri="Mastering Silverlight"
Description="49.95" />

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



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