我工作的一个Silverlight Web应用程序,类似于XML的工作原理:的Silverlight C#的LINQ to XML
<?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;
}
注意你并不需要所有的'Int32.Parse({expr}的。价值)' - 你可以只投了'XElement' - 简单得多,并给出了更清晰的米西行为ng元素(你可以强制转换为null等) – 2009-10-13 19:29:55
对于信息 - 使用强制转换(而不是解析)的另一个原因; 'DateTime' - 如果您投了,它会使用正确的xsd日期格式;-p – 2009-10-13 19:44:38
是的。比较查询,使用转换比解析更容易阅读。 – Jason 2009-10-14 14:47:28