0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    possible duplicate of [Data at the root level is invalid. Line 1, position 1 -why do I get this error while loading an xml file?](http://stackoverflow.com/questions/7544475/data-at-the-root-level-is-invalid-line-1-position-1-why-do-i-get-this-error-w) – Sam Jul 01 '15 at 14:27

2 Answers2

1

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();
Charles Mager
  • 25,735
  • 2
  • 35
  • 45
0

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