簡體   English   中英

使用LINQ從xml創建實體對象的最佳方法

[英]Best way to create entity objects from xml using LINQ

我有以下代碼用於從源XML創建對象列表。 我可以在var query變量中獲取require結果。 從此結果創建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();

    }

}

實體

 public class Video
 {
     public string MyTitle { get; set; }
     public string MyPath { get; set; }
 }

參考

  1. 在XDocument中查找和設置元素值的最有效方法是什么?
  2. 如何從XDocument對象獲取子元素列表?
  3. 從XML創建對象
  4. 具有XML的C#LINQ,無法將多個具有相同名稱的字段提取到對象中
  5. 如何獲得XElement的值而不是所有子節點的值?
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();

或不帶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();

基於方法的查詢:

var results = myDoc.Descendants("video")
                   .Select(v => new Video()
                                {
                                    MyTitle = (string)v.Attribute("title"),
                                    MyPath = (string)v.Attribute("path")
                                 }).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM