gpt4 book ai didi

c# - 使用 LINQ 从 xml 创建实体对象的最佳方法

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:13 25 4
gpt4 key购买 nike

我有以下代码用于从源 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();

}

}

实体

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

引用:

  1. What's the most efficient way to locate and set element values in an XDocument?
  2. How do I get a list of child elements from XDocument object?
  3. Creating objects from XML
  4. C# LINQ with XML, cannot extract multiple fields with same name into object
  5. How to get XElement's value and not value of all child-nodes?

最佳答案

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

关于c# - 使用 LINQ 从 xml 创建实体对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15380694/

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