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

renaming default namespaces for VSTO projects in VS2008

So here is the scenario , you are starting a VSTO project and decided that your default namespace is ExcelAddInTesterApp . You created the project and started coding the project. After several days , your boss called and said "hey marvin , make use of this namespace OurCompany.ExcelAddInTesterApp , we have to add our company name to it got it?" . You get back to your machine thinking its just a simple property just like any project you've been working on. So you right clicked the VSTO project and hit properties . Boom! What the F@#$? The default namespace textbox is disabled!!!!



I've been through this and I googled for ways to do it and ended up with a blog from a Microsoft MVP telling me it can't be done because it is disabled. Then I thought of Refactoring, the beauty and grandeur of the renaming process. I selected the namespace and hit the refactor menu hoping that this would solve the problem . Unfortunately , it did not rather it displayed the message box …

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

this year

.. i will learn new things, perhaps play a new instrument or go back to school.
.. i will find beauty on the open source community.
.. i will read more books and listen to more music.
.. i will pen more poems and possibly write more songs.
.. i will go for new distances and discover new terrains.
.. i will continue to pile running miles to stay fit and healthy.
.. i will strive to be free and make myself available to unknown future.
.. i will go out of my shell more often and be socially more open.

.. i will continue to grow and go with the changes of time.
.. i will be more patient and hopeful to things that may not even be possible.
.. i will be a better son, brother and more importantly a better father.
.. i will be closer with the great beyond.

.. i will continue to repair , refactor and upgrade myself to become a better version of me.