结合XML元素在MVC4模型

结合XML元素在MVC4模型

本文介绍了结合XML元素在MVC4模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜查,但找不到类似的事情,因为这可能是非常基本的。基本上,我试图从一个XML文件中读取的电影列表,然后将它传递回各​​类消费的模式。但我得到一个System.NullReferenceException:对象不设置到对象的实例。我(须藤)C#code看起来像这样

  VAR xmlDoc中=新的XmlDocument();
        xmlDoc.Load(C:\\\\ movies.xml);
        VAR movieModel =新MovieSummary();
        VAR MovieXML = xmlDoc.GetElementsByTagName(电影);
        INT I;        对于(i = 0; I< MovieXML.Count;我++)
        {
            。movieModel.Movies [我]。名称= MovieXML [I] [名称]的toString();
        }

我的模型看起来像这样

 命名空间movies.Models
 {     公共类MovieSummary
     {
         公开名单<电影及GT;电影{搞定;组; }
     }     公共类电影
     {
         公共字符串电影{搞定;组; }
     }
 }

XML文件看起来像

 <电影的xmlns =htt​​p://www.sitemaps.org/schemas/sitemap/0.9>
      <电影和GT;
       <名称>黑暗骑士< /名称>
  < /电影和GT;
  <电影和GT;
       <名称>钢铁侠< /名称>
  < /电影和GT;
 < /电影和GT;


解决方案

我认为你是用最好的XmlSerializer 如果您的XML文件的结构是相似的类通过继承。

编写一个反序列化的XML,以便您的类的功能。

 公共静态MovieSummary反序列化()
{
    XmlSerializer的序列化=新的XmlSerializer(typeof运算(MovieSummary));
    的TextReader的TextReader;    的TextReader =新的StreamReader(pathtoyourxmlfile);    MovieSummary总结=(MovieSummary)serializer.Deserialize(TextReader的);
    textReader.Close();
    返回总结;
}

希望帮助

I've searched but couldn't find anything similar as this is probably very basic. I'm basically trying to read a list of movies from an xml file and then to pass it back into a Model for various types of consumption. But I get a "System.NullReferenceException: Object reference not set to an instance of an object." My (sudo) c# code looks something like this

        var xmlDoc = new XmlDocument();
        xmlDoc.Load("c:\\movies.xml");
        var movieModel = new MovieSummary();
        var MovieXML = xmlDoc.GetElementsByTagName("movie");
        int i;

        for (i = 0; i < MovieXML.Count; i++)
        {
            movieModel.Movies[i].name = MovieXML[i]["name"].toString();
        }

my Model looks like this

 namespace movies.Models
 {

     public class MovieSummary
     {
         public List<Movie> Movies { get; set; }
     }

     public class Movie
     {
         public string movie { get; set; }
     }
 }

xml file looks like

 <movies xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
      <movie>
       <name>The Dark Knight</name>
  </movie>
  <movie>
       <name>Iron Man</name>
  </movie>
 </movies>
解决方案

I think you are better off with using XmlSerializer if the structure of your xml file is resembled in your classes by inheritance.

Write a function which Deserialize your xml to your classes.

public static MovieSummary Deserialize()
{
    XmlSerializer serializer = new XmlSerializer(typeof(MovieSummary));
    TextReader textReader;

    textReader = new StreamReader(pathtoyourxmlfile);

    MovieSummary summary = (MovieSummary)serializer.Deserialize(textReader);
    textReader.Close();
    return summary;
}

Hope that helps

这篇关于结合XML元素在MVC4模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:34