Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在MVC控制器中加载XML_C#_Xml_Asp.net Mvc_Razor - Fatal编程技术网

C# 在MVC控制器中加载XML

C# 在MVC控制器中加载XML,c#,xml,asp.net-mvc,razor,C#,Xml,Asp.net Mvc,Razor,我正在尝试在“HomeController”中的MVC中加载一个XML文档 我希望此文档加载到/Home/目录下的所有内容中,以便我的类: public HomeController() { } 在这里面,我有我想要连接到XML的代码: //Now set up the config xml read XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(HttpContext.Server.M

我正在尝试在“HomeController”中的MVC中加载一个XML文档

我希望此文档加载到/Home/目录下的所有内容中,以便我的类:

public HomeController()
        {  }
在这里面,我有我想要连接到XML的代码:

//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;
        }
XML的结构:

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

废话

我似乎找不到XML文件,如果它是一个Web应用程序,则会出现“对象设置为空引用”错误。检查web服务器上是否存在此文件路径。如果是WinForms应用程序,请使用ExecutionPath或环境变量获取所需的路径

如果(File.Exists(yourFilePathHere))而不是

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

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

哪一行导致null ref异常?如果xmldoc.Load找不到该文件,则会出现某种IO异常,而不是空引用。可能路径不正确。Load(HttpContext.Server.MapPath(“~/Content/settings.xml”);异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。源错误:第29行://现在设置配置xml读取第30行:XmlDocument xmldoc=new XmlDocument();第31行:xmldoc.Load(Server.MapPath(“~/Content/settings.xml”);使用调试器,尝试查找空值。如果需要,重构代码以使用如下变量:
var filePath=HttpContext.Server.MapPath(“~/Content/settings.xml”);Load(filePath)
为了检查文件是否真的找到了,还有,哪一行是第29行?出于某种原因,当我检查它时,httpContext是空的。第29行只是一个注释。“//现在设置刚刚从浏览器中选中的config xml read”,并且可以访问该文件。我想这可能与我调用文件的方式有关,所以尝试使用webrequest中的流而不是字符串。