我的想法是创建类,对应于你的 Xml 文件,一个版本类,一个工厂类。加载 xml 文件,然后将其传递给返回数据的类,我是这样做的:
版本类:
public class Version
{
public bool IsProduct { get; set; }
public string City { get; set; }
public List<Factory> Factories { get; set; }
//Create a version
public Version(XElement xVersion)
{
IsProduct = Convert.ToBoolean(xVersion.Element("Product").Value);
City = xVersion.Element("City").Value;
Factories = Factory.GetFactories(xVersion);
}
//Get the list of versions
public static List<Version> GetVersions(XElement xDocument)
{
if (xDocument == null)
return null;
List<Version> list = new List<Version>();
var xVersions = xDocument.Elements("Version");
foreach (var xVersion in xVersions)
{
list.Add(new Version(xVersion));
}
return list;
}
}
工厂类:
public class Factory
{
public string Name { get; set; }
public string Url { get; set; }
public string Thumbnail { get; set; }
public string Interval { get; set; }
//Create a factory
public Factory(XElement xFactory)
{
Name = xFactory.Attribute("Name").Value;
Url = xFactory.Attribute("Url").Value;
Thumbnail = xFactory.Attribute("Thumbnail").Value;
Interval = xFactory.Attribute("Interval").Value;
}
//Get the factories of a version
public static List<Factory> GetFactories(XElement xVersion)
{
var xFactories = xVersion.Elements("Factory");
if (xFactories == null)
return null;
List<Factory> list = new List<Factory>();
foreach (var xFactory in xFactories)
{
list.Add(new Factory(xFactory));
}
return list;
}
}
最后,在您的 MCV 控制器中:
private void myMethod()
{
var xDocument = XElement.Load("XmlFilePath");
var versions = Version.GetVersions(xDocument);
//And then, pass the -versions- to your typed view ^^
}