Skip to main content

My First LINQ to XML Experience : Creating XMLDocument the LINQ way

Here is my first post (from a series of i-dont-know-how-many) regarding LINQ . Im not a guru , Im just starting out with the technology . So comments are well appreciated .

Creating XMLDocument the preLINQ and LINQ way

This post will give the viewers the idea on what LINQ to XML has to offer . To be able to see the difference I am goig to implement the solution using the preLINQ way then move forward using LINQ . This is a simple console application made using VS2008 that simply create the XML document below :

<Persons>
  <Person Type="Faculty">
   <FirstName>Dugong</FirstName>
   <LastName>Valenciano</LastName>
  </Person>
  <Person Type="Student">
   <FirstName>Kokey</FirstName>
   <LastName>Donatelo</LastName>
  </Person>
</Persons>


The application calls two separate methods to build the document . The CreateXMLDocumentOldMethod() is the first method , this method uses the preLINQ method as shown by the code below :

   private static void CreateXMLDocumentOldMethod()
   {
        XmlElement person;
        XmlAttribute personAttribute;
        XmlElement firstName;
        XmlElement lastName;
        //create the document
        XmlDocument personList = new XmlDocument();
        //create the root node
        XmlElement persons = personList.CreateElement("Persons");
        personList.AppendChild(persons);
        //create the first element
        person = personList.CreateElement("Person");
        personAttribute = personList.CreateAttribute("Type");
        personAttribute.InnerText = "Faculty";
        person.Attributes.Append(personAttribute);
        firstName = personList.CreateElement("FirstName");
        firstName.InnerText = "Dugong";
        person.AppendChild(firstName);
        lastName = personList.CreateElement("LastName");
        lastName.InnerText = "Valenciano";
        person.AppendChild(lastName);
        persons.AppendChild(person);
        //create the second element
        person = personList.CreateElement("Person");
        personAttribute = personList.CreateAttribute("Type");
        personAttribute.InnerText = "Student";
        person.Attributes.Append(personAttribute);
        firstName = personList.CreateElement("FirstName");
        firstName.InnerText = "Kokey";
        person.AppendChild(firstName);
        lastName = personList.CreateElement("LastName");
        lastName.InnerText = "Donatelo";
        person.AppendChild(lastName);
        persons.AppendChild(person);
        //print it
        Console.WriteLine(personList.InnerXml.ToString());
   }
}

As you can see from the code , it is a nightmare to write , understand and maintain. What makes it more confusing is that it doesnt give you a clear picture of what the XML structure should look like .

Moving forward , below is the code for the method CreateXMLDocumentUsingLINQ(). This method uses the features associated with LINQ .

private static void CreateXMLDocumentUsingLINQ()
{
   XElement personList=
        new XElement("Persons",
            new XElement("Person",
               new XAttribute("Type","Faculty"),
               new XElement("FirstName","Dugong"),
               new XElement("LastName","Valenciano")),
            new XElement("Person",
               new XAttribute("Type","Student"),
               new XElement("FirstName","Kokey"),
               new XElement("LastName","Donatelo")));
   Console.WriteLine(personList.ToString());
}


See how straightforward the approach is . By just looking at the code , you could easily decipher which are elements and which are attributes . Unlike its predecessor , this new tecnology uses functional construction to build the XML tree. This allows the schema to be dictated as the XML objects are created and initialized at the same time in a single line of code . The type of object (i.e. XElement and XAttribute ) determines where in the schema the added object belongs . If for example you added an XAttribute object XAttrib to an XElement XElem1 then that XAttrib becomes an attribute of the element XElem1 . In the same manner as when an XElement XElemChild is added to an XElement XElemParent, then that element XElemeChild become a child element of the XElemParent . Pretty straightforward isnt it ?

You can download the source file here : LINQtoXML.Lesson1.zip

Note: The file is hosted on a free file hosting site so if the link expired email me at m3lles@yahoo.com .

I will be posting the next part of my LINQ to XML experience as soon as I have it .

Comments

Popular posts from this blog

Getting Started with Stateless : A Lightweight Workflow Library Alternative for .NET

Image Credit: https://www.pioneerrx.com A year ago, I was looking for a simple workflow manager for a project I was working. Its a medium sized application that involves tracking the state of assets in the system. Back in 2008, Microsoft (MS) introduced new technologies along with the release of Visual Studio 2008: Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF), and  Windows Workflow Foundation (WF). Having worked in a company utilizing mostly MS products for development, my first option was to go with WF. After doing some time reading and studying the library, I paused and decided it was too complex for my requirement. Using WF would be an overkill and the fact that it has, a rather, steep learning curve, there has to be another option. My mind toyed with the idea of developing a simple workflow library myself. It would be a learning experience but it might end up consuming a lot of time. Why reinvent the wheel? So I started querying the inte

Hiding Unwanted Python Folders and Files in Visual Studio Code

Visual Studio Code is a universal editor and pretty good at it. However, the explorer view maybe cluttered with the automatically generated folders and files confusing developers. Python is no different. Below are example files and folders generated by Python. The __pycache__ folder and *.pyc files  are totally unnecessary to the developer. To hide these files from the explorer view, we need to edit the settings.json for VSCode. Add the folder and the files as shown below: Copy and paste the lines below : "**/*.pyc" : { "when" : "$(basename).py" }, "**/__pycache__" : true

My First Blog for 2009

Im starting 2009 with a blog on foods. Since my 4 months voluntary exile in the US (hahaha), I started cooking ( full time! ) so Google is my cookbook and I am the chef ( sort of ). Yesterday , I was looking forward for another experiment on the kitchen lab (it gets messy sometimes) . What I have ? Pork belly , Chinese Okra , Squash . I was having doubts on whether the Chinese Okra is the same thing as the vegetable I know from the province , "kabatiti" . So after searching for "kabatiti" on the net , Google returned some informative links on some Ilocano Foods which made my day . Listed below are some Ilocano food worth mentioning . Abrao or Inabrao - assorted seasonal vegetables, typically malunggay, and that quintessentially Ilocano vegetable, saluyot, boiled in a bagoong and fish broth Ipon—tiny fish in season during the cold months Poki-Poki (also poqui-poqui), an innocent omelet made of eggplant sautéed with garlic, onions, tomatoes, and eggs Kabat