(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Using LINQ to XML in Silverlight

(11 votes)
Martin Mihaylov
>
Martin Mihaylov
Joined Oct 29, 2007
Articles:   50
Comments:   70
More Articles
11 comments   /   posted on Jul 14, 2008
Categories:   Data Access , General

This article is compatible with the latest version of Silverlight.


When working with data, it often comes in an XML format. So we have to serialize and deserialize it in order to use it. There are several ways of doing that – for example: DOM, XQuery, XSLT. DOM is the oldest from the three, but still can do the work. XQuery and XSLT are not very easy to use and require some time to master. In .NET 3.5 a big programming model improvement was made with the LINQ - Language-Integrated Query. It can be used for objects, databases and XML. In the following article I will try to explain the basics of using LINQ to XML and if you are new to it, I hope it will help you to improve your programming experience.

Introduction

LINQ to XML allows us to create, read and edit XML files and what’s more important - it’s done in a very easy and understandable way. To use LINQ to XML you should add a reference to the System.Xml.Linq.dll (for the XDocument and the other classes) and use the System.Linq namespace (for the LINQ syntax).

A brief overview of the most important methods of XElement and XDocument

  • Add(object content) – adds the new content as a child of the element
  • Remove() – Remove this element from its parent
  • Descendents( XName name ) – returns a collection of all descendents of this element, which names match the argument, in document order
  • Element( XName name ) – returns the first child that has a matching name
  • Elements( XName name ) - returns a collection of all children of this element, which name matches the argument, in document order
  • Nodes() – returns a collection of all children of the current element in document order

Creating an XML file

So let’s have a simple class Person:

 public class Person
 {
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public Location Address { get; set; }
 }
 
 public class Location
 {
      public string Country { get; set; }
      public string City { get; set; }
  }

And we create an object of type Person:

 Person p1 = new Person()
             {
                 FirstName = "Martin",
                 LastName = "Mihaylov",
                 Address = new Location()
                 {
                     City = "Sofia",
                     Country = "Bulgaria"
                 }
              };

Now let’s try to create an XML from it. For that purpose we use XElement and XAttribute objects:

 XElement persons =
         new XElement( "persons",
             new XElement( "person",
                 new XElement( "firstName", p1.FirstName ),
                 new XElement( "lastName", p1.LastName ),
                 new XElement( "address",
                     new XAttribute( "city", p1.Address.City ),
                     new XAttribute( "country", p1.Address.Country ) ) ) );

We simply create an element “persons” using the XElement object and then nest other elements in it. We can also create properties for the elements thanks to the XAttribute object. We can also use the XDeclaration object to define our xml document and XComment to add a comment to the xml document. Here it is:

 XDocument myXml = new XDocument( new XDeclaration( "1.0", "utf-8", "yes" ),
                 new XComment( "A Comment in the XML" ), persons );

So the final output should look like this:

 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
 <!-- A Comment in the XML -->
 <persons>
     <person>
           <firstName>Martin</firstName>
           <lastName>Mihaylov</lastName>
           <address city="Sofia" country="Bulgaria" />
     </person>
 </persons>

Adding an element to the XDocument

First we find the element we want to add something to and then we use its Add method to add our new element. Here is an example:

 myXml.Element( "persons" ).Add( new XElement( "person",
                         new XElement( "firstName", p2.FirstName ),
                         new XElement( "lastName", p2.LastName ),
                         new XElement( "address",
                             new XAttribute( "city", p2.Address.City ),
                             new XAttribute( "country", p2.Address.Country ) ) ) );

Removing an element form the XDocument

To remove an element or attribute you must navigate to the desired element and then call its Remove method:

 myXml.Element( "persons" ).Element( "person" ).Remove();

This will remove the first element with name “person” in “persons”.

Reading an XML file

Before reading you should load your XML file to an XElement or XDocument object. This can be done with the Load method. You can input from string, from TextReader, from XMLReader and of course from file. Here is an Example:

 XDocument myXML = XDocument.Load( "MyXML.xml" );

Now let’s try to read the contents of an XML file. For this example we use the XML string we’ve already created in the beginning of the article. Thanks to LINQ we can use the standard query operators: from, in, select. Because of that to take the information you need from an XML file becomes fairly easy:

 List<Person> personsList =
             ( from person in myXml.Descendants( "person" )
              where (( string )person.Element( "address" ).Attribute( "country" )).Equals( "Bulgaria" )
              select new Person()
                  {
                      FirstName = person.Element( "firstName" ).Value,
                      LastName = person.Element( "lastName" ).Value,
                      Address = new Location()
                      {
                           City = person.Element( "address" ).Attribute( "city" ).Value,
                           Country = person.Element( "address" ).Attribute( "country" ).Value
                       }
                   } ).ToList();

The Descendants method returns all child elements that have name “person” (in our case). Then from each descendent that has an "address" element with "country" property set to "Bulgaria" we create a new object of type Person and set its properties. The output is a list of objects.

References

http://msdn.microsoft.com/en-us/library/bb308960.aspx - probably almost everything about LINQ to XML you want to know ... and more

http://msdn.microsoft.com/en-us/library/cc645034(VS.95).aspx - How to: Load an XML File from an Arbitrary URI Location

http://msdn.microsoft.com/en-us/library/cc189044(VS.95).aspx - How to: Create Dynamic XAML with LINQ to XML

Summary

These are just the basics of using LINQ to XML. It’s really easy learning the basics of it, but there is a lot more and if I write it here it will make the article more complicated and heavier. The main purpose of the article is to be a quick start for people have just begun using this technology. So maybe I’ll write additional articles about LINQ to XML which will take a deeper look in it. If you are impatient and want to learn more now just take a look at the references above.


Subscribe

Comments

  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by ngocthanhtnt@gmail.com on Oct 10, 2008 19:57

    Hi everyboy!

    I have done as example but not load data in XML file into datagrid

     

    pls, help me!

  • Enrai

    RE: Using LINQ to XML in Silverlight 2


    posted by Enrai on Oct 14, 2008 13:23

    If you want to load the data, read from the XML file, into a DataGrid, take a look at this article.

  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by Dheeraj on Mar 05, 2009 00:59

    Very useful and short blog on working with XML. Thanks for this

  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by Mohammad on Apr 04, 2009 17:22
    Good.

    Thanks

  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by shobha on Oct 28, 2009 07:29

    Am new to silverlight. can anyone help me how to store custom usercontrols's data to XML file.

    The usercontrols here are basically used for creating flow charts.

  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by test on Dec 01, 2009 02:23
    Hi - I son't know what am I doing wrong!

    here is my code - It reads xml file properly but LinQ gives me 0 count

            private static IList<Questions> ReadXMLFile(int CurrentQuestion)
            {
            try
                {
                    XDocument QuestionXML = XDocument.Load("Question.xml");
                    List<Questions> questionList =
                        ( from question in QuestionXML.Descendants( "question" )
                            where ((question.Element( "id" )).Equals(CurrentQuestion.ToString()))
                            select new Questions()
                      {
                            id= int.Parse(question.Element( "id" ).Value),
                            QuestionDesc = question.Element( "questiondescription" ).Value,        
                      } ).ToList();
                    return questionList;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }   

    When passing 1 or 2 as currentquestion QuestionList returns 0 count

     Here is my XML

     

    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <questions>
               <question>
            <id>1</id>
                    <questiondescription>First Question</questiondescription>
           </question>
           <question>
            <id>2</id>
                    <questiondescription>Second Question</questiondescription>
           </question>
           </questions>
  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by test on Dec 01, 2009 02:35
    Ignore previous comments - the problem was here where ((question.Element( "id" )).Equals(CurrentQuestion.ToString()))

    fixed by

     where (((String) question.Element( "id" )).Equals(CurrentQuestion.ToString()))

    Thanks

  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by Zinnsoldat on Jan 27, 2010 16:21

    Hi!

    I'm trying to make a new Object of XDocument but VS tells me that there is not such a class?
    Am I to stupid or whats the problem here?

    regards

  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by Suresh on May 18, 2010 14:40
    I'm trying to retrieve data from xml into chat controles, but XDocument object not created in my application, I imported Using System.Xml  any  ......
  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by Rahul on Jun 03, 2010 08:06

    <Exam>

    <Q

     

     

    uestions name="1" >

     

    <question

     

     

    name="B"></member>

     

    <question

     

     

    name="C"></member>

     

    <question

     

     

    name="D"></member>

     

    </Questions

     

     

    >

    <Questions name="2">

    </Questions>

    </Exam>

     

    Here how to get the <Questions name="1" >.

    Actually I am bindin this xml to treeview. I am selecting Element "C" on the SelectionChanged Event of treeview. Here I want to get the Ancestors of C. ie <Questions name="A" >. If Use Ancestors mathod then I will get XElement like this

    <Questions name="1" >

     

    <question

     

     

    name="B"></member>

     

    <question

     

     

    name="C"></member>

     

    <question

     

     

    name="D"></member>

     

    </Questions

     

     

    >

    <Questions name="2">

    </Questions>

     

    But I want like this 

    <Questions name="1" >

     

    <question

     

     

    name="B"></member>

     

    <question

     

     

    name="C"></member>

     

    <question

     

     

    name="D"></member>

     

    </Questions

     

     

    >

  • -_-

    RE: Using LINQ to XML in Silverlight 2


    posted by ashoka on Sep 06, 2010 14:22
     so nice

Add Comment

Login to comment:
  *      *