简体   繁体   English

将xml元素绑定到MVC4中的模型

[英]binding xml elements to model in MVC4

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. 我基本上试图从xml文件中读取电影列表,然后将其传递回模型中以用于各种类型的消费。 But I get a "System.NullReferenceException: Object reference not set to an instance of an object." 但我得到一个“System.NullReferenceException:对象引用未设置为对象的实例。” My (sudo) c# code looks something like this 我的(sudo)c#代码看起来像这样

        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 xml文件看起来像

 <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. 我认为如果你的xml文件的结构通过继承类似于你的类,那么你最好使用XmlSerializer

Write a function which Deserialize your xml to your classes. 编写一个函数,将xml反序列化到类中。

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 希望有所帮助

If you are ONLY going to ever be loading a list of movies from an xml file, and that't it, you should check out the following link on MSDN: http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.getelementsbytagname%28v=vs.71%29.aspx 如果您只是要从xml文件中加载电影列表,那不是,您应该查看MSDN上的以下链接: http//msdn.microsoft.com/en-us/library/ system.xml.xmldocument.getelementsbytagname%28V = vs.71%29.aspx

This would be a solution for that approach: 这将是该方法的解决方案:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load("c:\\movies.xml");
            var movieModel = new MovieSummary();
            var MovieXML = xmlDoc.GetElementsByTagName("movie");
            movieModel.Movies = new List<Movie>();
            foreach (XmlElement element in MovieXML)
            {
                movieModel.Movies.Add(new Movie(){movie = element.InnerText});                
            }
            //for (i = 0; i < MovieXML.Count; i++)
            //{
            //    movieModel.Movies[i].name = MovieXML[i]["name"].toString();
            //}
        }
    }
}

If you are going to plan on loading anything more than just movies from the xml file or you think you'll ever need more flexibility in loading multiple nodes from multiple xml files, I'd advise using the xmlserialization ability of .NET via the xsd.exe tool. 如果您计划加载除xml文件中的电影之外的任何内容,或者您​​认为从多个xml文件加载多个节点需要更多的灵活性,我建议通过xsd使用.NET的xmlserialization功能.exe工具。 Do your xml files adhere to a common xsd schema. 您的xml文件是否遵循常见的xsd架构。 If they dont, dont worry, you can create a common schema for your xml files using xsd.exe (its part of visual studio). 如果他们不这样做,不要担心,您可以使用xsd.exe(它是visual studio的一部分)为您的xml文件创建一个通用模式。 Once you have generated the xsd file from your sample xml file, you can use that xsd file to generate classes using that same xsd.exe tool. 从示例xml文件生成xsd文件后,可以使用该xsd文件使用相同的xsd.exe工具生成类。

Once that is done, you can add the generated class or classes to your model as members, wrap them as you see fit, and bulk load the data from the xml file into the member classes with a few lines of code. 完成后,您可以将生成的一个或多个类作为成员添加到模型中,根据需要将它们包装起来,然后使用几行代码将数据从xml文件批量加载到成员类中。 And that will work for any xml file so long as it adheres to said xsd file. 这适用于任何xml文件,只要它遵守所述xsd文件即可。 You an also load and unload the data to and from xml file to and from classes using serializer classes. 您还可以使用序列化程序类在xml文件中加载数据或从数据库中卸载数据。

There are many ways to do what you are talking about, and I've tried many ways. 有很多方法可以做你正在谈论的事情,我已经尝试了很多方法。 However, this by far the best way to do things because it allows you to load as many different xml files as you want without having to rewrite the methods that load the xml (Again, as long as what you're loading adheres to the xsd file). 但是,这是迄今为止最好的处理方式,因为它允许您根据需要加载任意数量的不同xml文件,而无需重写加载xml的方法(同样,只要您加载的内容遵循xsd)文件)。

http://msdn.microsoft.com/en-us/library/x6c1kb0s%28v=vs.71%29.aspx http://msdn.microsoft.com/en-us/library/x6c1kb0s%28v=vs.71%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM