gpt4 book ai didi

c# - 在 C# MVC 中将 XML 数据绑定(bind)到模型

转载 作者:行者123 更新时间:2023-11-30 14:55:15 24 4
gpt4 key购买 nike

我希望将 XML 绑定(bind)到 C# MVC 应用程序中的模型。

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>

型号:

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; }
}

损坏的绑定(bind):

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?*
}

我是 C# 的新手,正在寻找将数据从 XML 绑定(bind)到 person var 的最佳方法。稍后我将循环并输出到 HTML 表格中。

任何帮助都会很棒。

最佳答案

你必须这样做:

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()
};

工作 fiddle :

https://dotnetfiddle.net/2uKdd5

关于c# - 在 C# MVC 中将 XML 数据绑定(bind)到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25805164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com