Load XML in MVC Controller
18,249
Solution 1
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))
Solution 2
Instead of
xmldoc.Load(HttpContext.Server.MapPath("~/Content/settings.xml"));
try with only
xmldoc.Load(Server.MapPath("~/Content/settings.xml"));
Related videos on Youtube
Author by
JustAnotherDeveloper
Developer and Geek who knows way too many pointless facts and not enough code...
Updated on May 25, 2022Comments
-
JustAnotherDeveloper about 2 years
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
-
Ben Robinson over 12 yearsWhat line causes the null ref exception? If xmldoc.Load couldn't find the file you would get some kind of IO exception not a null ref.
-
Thinhbk over 12 yearsmaybe the Path is not correct. xmldoc.Load(HttpContext.Server.MapPath("~/Content/settings.xml"));
-
JustAnotherDeveloper over 12 yearsException Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 29: //Now set up the config xml read Line 30: XmlDocument xmldoc = new XmlDocument(); Line 31: xmldoc.Load(Server.MapPath("~/Content/settings.xml"));
-
Steve B over 12 yearsusing the debugger, try to find what is null. If required, refactor the code to use a variable like this :
var filePath = HttpContext.Server.MapPath("~/Content/settings.xml"); xmldoc.Load(filePath);
in order to check if the file is actually found, also, which line is the 29th ? -
JustAnotherDeveloper over 12 yearsFor some reason, httpContext is null when I inspect it. line 29 is just a comment. "//Now set up the config xml read"
-
-
JustAnotherDeveloper over 12 yearsJust checked from the browser, and the file is accessible. I think it may have something to do with how I am calling the file?
-
Scarlaxx over 12 yearsSo try to use a stream from webrequest instead of the string.