How Read Xml File from Project Directory in C#?

I need to know about to read xml file from project directory as shown below code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using crudpartialviewsjqueryajax.Models;
using System.Data;
using System.Xml;

namespace crudpartialviewsjqueryajax.Controllers
{
    public class snehprajapatController : Controller
    {
        public void getinstructors()
        {
            try
            {
                List<string> name = null;
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(@"~\App_Data\Trainings.xml");//Here given xml path location
                XmlNodeList xnList = xml.SelectNodes("/Trainings/Training");

                foreach (XmlNode xn in xnList)
                {
                    new List<string>{ xn["name"].InnerText };
                }
            
                //return name;
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}

I'm getting this error:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

Additional information: Data at the root level is invalid. Line 1, position 1.

Please see the above code and suggest what to do to fix this?

Thanks in advance

Upvotes: 0

Views: 9601

Answers (2)

Charles Mager
Charles Mager

Reputation: 26213

LoadXml is for loading a literal XML string, not for pointing to a file path. Your path is, not surprisingly, not valid XML. You can use xml.Load("...") to load into an XmlDocument from a file.

However, I'd strongly suggest you use LINQ to XML instead unless you have a very good reason to be using the old XmlDocument API. I've made a guess based on your code, though this may not work correctly if your XML isn't structured this way.

var doc = XDocument.Load(@"~\App_Data\Trainings.xml");

var instructorNames = doc.Descendants("Training")
    .Elements("name")
    .Select(e => e.Value)
    .ToList();

Upvotes: 1

Zakaria Smahi
Zakaria Smahi

Reputation: 136

You should replace the xml.LoadXml by the method xml.Load because : XmlDocument.Load : is for loading XML either from a stream, TextReader, path/URL, or XmlReader. While the XmlDocument.LoadXml is for loading the XML contained within a string.

so your code should be like that :

xml.Load(@"~\App_Data\Trainings.xml");//Here given xml path location

Upvotes: 0

Related Questions