Random Post : LINQ to XML

14 07 2008

Thought of refreshing my LINQ to XML skills and here is the outcome – another blog post today! 8)

Here is our sample XML file (never mind where it came from or why it is complex)

<?xml version="1.0" encoding="utf-8" ?>
<Output_Message>
    <Dataset>
        <Row>
            <Persons_Current_Name>
                <Name>
                    <Surname>John</Surname>
                    <GivenName>Samuels</GivenName>
                </Name>
            </Persons_Current_Name>
            <Persons_Name_At_Birth>
                <Name>
                    <Surname></Surname>
                    <GivenName>John</GivenName>
                </Name>
            </Persons_Name_At_Birth>
            <DateOfBirth>1865-07-31</DateOfBirth>
        </Row>
    </Dataset>
    <StatusInformation>
        <Status>OK</Status>
        <Alive>YES</Alive>
    </StatusInformation>
</Output_Message>

I am going to query each element (as listed below) and display their values

  • Persons_Current_Name
  • Persons_Name_At_Birth, and
  • DateOfBirth

Our first step would be to load this XML file. We can make use of XDocument to load the whole XML file.

XDocument mainXMLDoc
         = XDocument.Load("Input.xml");

To start with, let us traverse all the nodes and display their values

//Traversing the whole XML
Console.WriteLine("XML Traverse");
Console.WriteLine();
foreach (XElement xelement in
                   mainXMLDoc.Descendants())
{
    Console.WriteLine("{0} : {0}",
              xelement.Name, xelement.Value);
}

Looks simple, isn’t it πŸ™‚

Next, let us get the value of Persons_Current_Name. I already have a class called Name, which is shown below:

public class Name
{
    public String Surname { get; set; }
    public String GivenName { get; set; }
}

How do we directly query Persons_Current_Name element? Below is the very straight forward (ugly) code πŸ˜€

//Persons Current Name
// The Ugly Way
XElement current_name =
    mainXMLDoc.Root
        .Element("Dataset")
        .Element("Row")
        .Element("Persons_Current_Name")
        .Element("Name");
Name persons_current_name = new Name
    {
             Surname =
                  current_name.Element("Surname").Value,
             GivenName =
                   current_name.Element("GivenName").Value
    };

Well, I really don’t like to code this way. Do we have any another option? Yes, we do! 8)

//Persons Current Name
// The Neat Way
Name persons_current_name =
    (from c in mainXMLDoc.Descendants()
     where c.Name == "Persons_Current_Name"
     select new Name
           {
                 Surname =
                      c.Element("Name").Element("Surname").Value,
                 GivenName =
                      c.Element("Name").Element("GivenName").Value
            }).FirstOrDefault();

The above code certainly looks better than our previous code πŸ™‚

Similarly for DateOfBirth,

//Date of Birth
String[] strDob =
    (from c in mainXMLDoc.Descendants()
     where c.Name == "DateOfBirth"
     select c.Value).FirstOrDefault().Split('-');
DateTime dob = new DateTime(Convert.ToInt32(strDob[0]),
    Convert.ToInt32(strDob[1]),
    Convert.ToInt32(strDob[2]));

All looks good, but wait! What to do if I have my XML in string format ? How do I load it? Dont panic, you can use the same XDocument to load the XML in the string format πŸ™‚

XDocument mainXMLDoc =
         XDocument.Parse(strXML);
Advertisements

Actions

Information

3 responses

3 09 2010
sdfasd

`

3 09 2010
sdfasd

!

18 06 2011
fullman

sorry, did not work, had an exception with the date format.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: