查询 XML 到 Linq 的后代
我有以下 xml 数据:
<portfolio>
<item>
<title>Site</title>
<description>Site.com is a </description>
<url>http://www.site.com</url>
<photos>
<photo url="http://www.site.com/site/thumbnail.png" thumbnail="true" description="Main" />
<photo url="http://www.site.com/site/1.png" thumbnail="false" description="Main" />
</photos>
</item>
</portfolio>
在 c# 中,我使用以下链接查询:
List<PortfolioItem> list = new List<PortfolioItem>();
XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/app_data/portfolio.xml"));
list = (from portfolio in xmlDoc.Descendants("item")
select new PortfolioItem()
{
Title = portfolio.Element("title").Value,
Description = portfolio.Element("description").Value,
Url = portfolio.Element("url").Value
}).ToList();
如何查询照片节点?在 PortfolioItem 类中,我有一个属性:
List
任何想法将不胜感激!
I have the following xml data:
<portfolio>
<item>
<title>Site</title>
<description>Site.com is a </description>
<url>http://www.site.com</url>
<photos>
<photo url="http://www.site.com/site/thumbnail.png" thumbnail="true" description="Main" />
<photo url="http://www.site.com/site/1.png" thumbnail="false" description="Main" />
</photos>
</item>
</portfolio>
In c# I am using the following link query:
List<PortfolioItem> list = new List<PortfolioItem>();
XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/app_data/portfolio.xml"));
list = (from portfolio in xmlDoc.Descendants("item")
select new PortfolioItem()
{
Title = portfolio.Element("title").Value,
Description = portfolio.Element("description").Value,
Url = portfolio.Element("url").Value
}).ToList();
How do I go about querying the photos node? In the PortfolioItem class I have a property:
List<Photo> Photos {get;set;}
Any ideas would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我对您的 photo 类做出一些假设,假设为了这个答案,您将在构造函数中初始化 url,并通过其属性初始化另外两个类。
最直接的方法就是考虑在邮件 linq 查询中返回一个 Photos 属性,并使用简单的子查询创建它。
这是一个了解闭包概念的好机会 在 LINQ 中(如果您还没有这样做的话)。
I'm making some assumptions about your photo class, assuming for the sake of this answer that you would initialize url in the constructor, and the other two by their properties.
The most straightforward way is just to consider Photos one more property to return in your mail linq query, and create it with a simple sub-query.
A good opportunity to check out the concept of closures in LINQ if you haven't already.
假设您的 Photo 类如下所示:
您可以这样做:
Assuming that your Photo class looks like this:
You can do it like this:
不像其他类那么快,但又非常相似:
如果您的 PortfolioItem 和 Photo 类如下所示:
然后查询照片节点并填充照片列表,如下所示:
Not as fast as the others but again something very similar:
If your PortfolioItem and Photo classes look like this:
Then query the photos node and populate the Photos List like so: