Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load XML in MVC Controller

I am trying to load up an XML document in MVC in the "HomeController"

I want this document to load up in everything under the /Home/ directory so have my class:

public HomeController()
        {  }

And inside this I have the code that I want to connect to the XML with:

//Now set up the config xml read
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(HttpContext.Server.MapPath("~/Content/settings.xml"));
        XmlNodeList settings = xmldoc.SelectNodes("/settings");
        XmlNodeList defaults = xmldoc.GetElementsByTagName("default");
        foreach (XmlNode node in defaults)
        {
            string def_WebPageName = node["WebPageName "].InnerText;
        }

Structure of the XML:

<settings>
<defaults>
  <WebPageName>blah</WebPageName>
</defaults>

I cannot seem to locate theXML file, keep getting a "Object set to null reference" error

like image 504
JustAnotherDeveloper Avatar asked Jul 16 '26 10:07

JustAnotherDeveloper


2 Answers

Instead of

xmldoc.Load(HttpContext.Server.MapPath("~/Content/settings.xml"));

try with only

xmldoc.Load(Server.MapPath("~/Content/settings.xml"));
like image 128
Iridio Avatar answered Jul 18 '26 01:07

Iridio


If it is a Web app you get somthing like http://yoursite/Content/settings.xml. Check whether this file path exists on the web server. If it is a WinForms app use ExecutionPath or Environment variables to get the path you need.

You should also use something like if(File.Exists(yourFilePathHere))

like image 32
Scarlaxx Avatar answered Jul 18 '26 00:07

Scarlaxx