我有以下代码用于从源创建对象列表XML.我可以在var query变量中得到需求结果.List<Video>从这个结果创建一个最好的方法是什么?
注意:Method Chaining如果可能,请选择方法.
码
class Program
{
static void Main(string[] args)
{
string xmlStringInput = @"<videoShop>
<video title=""video1"" path=""videos\video1.wma""><Director>Speilberg</Director></video>
<video title=""video2"" path=""videos\video2.wma""/>
</videoShop>";
XDocument myDoc = XDocument.Parse(xmlStringInput);
var videoElements = (from video in myDoc.Descendants("video") select video).ToList();
foreach (var videoEle in videoElements)
{
//System.Xml.XPath namespace for XPathSelectElement
var directorName = videoEle.XPathSelectElement(@"Director");
}
var query = from video in myDoc.Descendants("video")
select new
{
MyTitle = video.Attribute("title").Value,
MyPath = video.Attribute("path").Value
};
//IEnumerable<XElement> elements = (IEnumerable<XElement>)query;
//List<Video> videoLibrary = (List<Video>)query.ToList<Video>();
Console.WriteLine(query);
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
实体
public class Video
{
public string MyTitle { get; set; }
public string MyPath { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
参考:
var query = from vin myDoc.Descendants("video")
select new Video
{
MyTitle = (string)v.Attribute("title"),
MyPath = (string)v.Attribute("path")
};
// var means List<Video> here
var results = query.ToList();
Run Code Online (Sandbox Code Playgroud)
或者没有query变量:
// var means List<Video> here
var results = (from vin myDoc.Descendants("video")
select new Video
{
MyTitle = (string)v.Attribute("title"),
MyPath = (string)v.Attribute("path")
}).ToList();
Run Code Online (Sandbox Code Playgroud)
基于方法的查询:
var results = myDoc.Descendants("video")
.Select(v => new Video()
{
MyTitle = (string)v.Attribute("title"),
MyPath = (string)v.Attribute("path")
}).ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1983 次 |
| 最近记录: |