简体   繁体   English

将XML数据绑定到C#MVC中的Model

[英]Binding XML data to Model in C# MVC

I'm looking to bind XML to Model in C# MVC app. 我希望在C#MVC应用程序中将XML绑定到Model。

XML: XML:

<people>  
    <person>
        <name>Mr Brown</name>
        <age>40</age>
        <hobby>
            <title>Eating</title>
            <description>eats a lot</description>
        </hobby>
        <hobby>
            <title>Sleeping</title>
            <description>sleeps a lot</description>
        </hobby>
    </person>
    <person>
        <name>Mr White</name>
        <age>40</age>
        <hobby>
            <title>Skiing</title>
            <description>more details on this</description>
        </hobby>
        <hobby>
            <title>Football</title>
            <description>watches football</description>
        </hobby>
    </person>
</people>

Model: 模型:

public class People
{
    public string Name { get; set; }
    public string Age { get; set; }
    public IList<Hobbies> Hobby {get; set; }
}
public class Hobbies
{
    public string Title { get; set; }
    public string Description { get; set; }
}

Broken Binding: 破坏绑定:

var person = from a in xml.Descendants("person")
select new People 
{
    Name = a.Element("name").Value,
    Age = a.Element("age").Value,
    Hobby = *WHAT GOES HERE?*
}

I'n new to C# and looking for the best way to bind the data from the XML to the person var. 我是C#的新手,正在寻找将数据从XML绑定到person var的最佳方法。 Which I'll later loop over and output in an HTML table. 我稍后将循环并在HTML表格中输出。

Any help would be great. 任何帮助都会很棒。

You have to do it this way: 你必须这样做:

var person = from a in xml.Descendants("person")
              select new People 
              {
                Name = a.Element("name").Value,
                Age = a.Element("age").Value,
                Hobby = a.Descendants("hobby")
                          .Select(x=> new Hobbies
                                       {
                                         Title =x.Element("title").Value,
                                         Description = x.Element("description").Value
                                       }).ToList()
               };

WORKING FIDDLE: 工作时尚:

https://dotnetfiddle.net/2uKdd5 https://dotnetfiddle.net/2uKdd5

Looks like you want standard XML deserialization. 看起来你想要标准的XML反序列化。 Some good answers on the best way to do that here 关于在这里做到这一点的最佳方法的一些好的答案

I would use XmlSerializer to load from Xml and to save to xml. 我会使用XmlSerializer从Xml加载并保存到xml。 You can derive People from this class for example (SerializeManagement) : 例如,您可以从此类派生人员(SerializeManagement):

public class SerializeManagement<T>
{
    public static T ReadFromXML(string iPath)
     {
        T val = default(T);
        try
        {
            // load from XML
            using (var sw = new StreamReader(iPath, Encoding.Default))
            {
                var ser = new XmlSerializer(typeof(T));
                val = (T)ser.Deserialize(sw);
            }
        }
        catch
        {
            Console.WriteLine("Problem reading from xml data file.");
        }

        return val;
    }

    public void SaveToXML(string iPath)

    {
        try
        {
            //TODO => using
            var sw = new StreamWriter(iPath, false, Encoding.Default);
            var ser = new XmlSerializer(typeof(T));
            ser.Serialize(sw, this);
            sw.Close();
        }
        catch
        {
            Console.WriteLine("Problem saving to xml data file.");
        }
    }
}

If you encounter problems, this could be because of your model definition or xml structure : 如果遇到问题,可能是因为您的模型定义或xml结构:

Then you can : 然后你可以 :

1) Generate c# class from the xml using xsd utility; 1)使用xsd实用程序从xml生成c#类;

2) Generate XML from existing class using SaveToXML. 2)使用SaveToXML从现有类生成XML。 That way you are sure the XML structure is compliant with your model. 这样您就可以确保XML结构符合您的模型。

Enjoy ! 请享用 !

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

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