Reading XML file in c#

Hello friends,

Today i will show you an example of reading xml file. To generate xml file read my previous blog.

I know there are many ways to read xml. But today we will use xDocument to read xml file.

Following is xml file we have generated.

    Sunil Gavaskar

Now, to read this xml we will use following function.

        public string xmlRead()
                StringBuilder xmlData = new StringBuilder();

                XmlDocument oReqDoc = new XmlDocument();

                XDocument rcvDoc = XDocument.Parse(oReqDoc.InnerXml);

                foreach (var itemTrn in rcvDoc.Descendants("Content").Descendants("Customer"))

                    xmlData.AppendLine(" Gender = " + itemTrn.Element("Gender").Value.ToString());
                    xmlData.AppendLine(" Firstname = " + itemTrn.Element("Firstname").Value);
                    xmlData.AppendLine(" Lastname = " + Convert.ToString(itemTrn.Element("Lastname").Value));
                    xmlData.AppendLine(" Mail = " + Convert.ToString(itemTrn.Element("Mail").Value));
                    xmlData.AppendLine(" AccountName = " + Convert.ToString(itemTrn.Element("AccountName").Value));
                    xmlData.AppendLine(" Amount = " + Convert.ToInt64(itemTrn.Element("Amount").Value));
                    xmlData.AppendLine(" Currency = " + Convert.ToString(itemTrn.Element("Amount").Attribute("Currency").Value));
                    xmlData.AppendLine(" CollectDate = " + Convert.ToDateTime(itemTrn.Element("CollectDate").Value));

                    // your code goes here

                return xmlData.ToString();
            catch (Exception ex)
                throw ex;

In above code i have load xml document and parse it in xDocument. Then by Descendants method you can read xml data you want. Descendants method is use to read specific data element from xml documents.

Some have error like data at the root level is invalid. line 1 position 1 it will occurs when you are using LoadXML method. If you will getting this error use Load method and error will gone.

Hope, it will help you.