gpt4 book ai didi

c# - Silverlight C# LINQ to XML

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

我正在开发一个使用 XML 的 Silverlight 网络应用程序,类似于:

<?xml version="1.0" encoding="UTF-8" ?> 
<ProjectList>
<Type>web</Type>
<Project>
<Id>1</Id>
<Name>test web project</Name>
<Description>test web project</Description>
<ScreenshotList>
<Screenshot>
<Path>screen1.jpg</Path>
<Description>This a description of screen 1</Description>
</Screenshot>
<Screenshot>
<Path>screen2.jpg</Path>
<Description>This a description of screen 2</Description>
</Screenshot>
<Thumb>noThumb.jpg</Thumb>
</ScreenshotList>
</Project>
</ProjectList>

我想为 XML 中的每个项目元素创建一个新对象。我有一个名为 project 的类,其中包含 id、name、description、thumb 字段和所有屏幕截图的列表。

我当前的 LINQ 代码如下所示:

var projects = from project in xDoc.Root.Elements("Project")
select new Project(
Int32.Parse(project.Element("Id").Value, CultureInfo.InvariantCulture),
project.Element("Name").Value,
project.Element("Description").Value,
project.Element("ScreenshotList").Element("Thumb").Value
);

无论如何,我是否可以轻松获取屏幕截图并将它们添加到这个查询中项目实例的列表中?

编辑 - 添加项目构造函数
public Project(int id, string name, string description, string thumbPath)
{
this.id = id;
this.name = name;
this.description = description;
this.thumbPath = thumbPath;
}

最佳答案

类似于:

    var projects = from project in xDoc.Root.Elements("Project")
let list = project.Element("ScreenshotList")
select new Project(
(int) project.Element("Id"),
(string)project.Element("Name"),
(string)project.Element("Description"),
(string)list.Element("Thumb"),
from scr in list.Elements("Screenshot")
select new Screenshot(
(string)scr.Element("Path"),
(string)scr.Element("Description")
)
);

基于以下类型:

class Project {
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Thumb { get; set; }
public List<Screenshot> Screenshots { get; private set; }
public Project( int id, string name, string description, string thumb,
IEnumerable<Screenshot> screenshots) {
this.Id = id;
this.Name = name;
this.Description = description;
this.Thumb = thumb;
this.Screenshots = screenshots == null ? new List<Screenshot>()
: new List<Screenshot>(screenshots);
}
}
class Screenshot {
public string Path { get; set; }
public string Description { get; set; }
public Screenshot(string path,string description) {
this.Path = path;
this.Description = description;
}
}

关于c# - Silverlight C# LINQ to XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1562345/

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