我又来了...... 我有一个XML文件,其中包含不同的类别,我想查询不同的属性。
<item>
<title>Industries</title>
<category type="Channel">Automotive</category>
<category type="Type">Cars</category>
<category type="Token">Article</category>
<category type="SpecialToken">News</category>
<guid>637f0dd7-57a0-4001-8272-f0fba60feba1</guid>
</item>
在SQL中我会写类似的东西。
select * from articles where channel = 'Automative' AND type = 'Cars' etc. etc.
如何使用linq实现这一目标? 我尝试了以下查询,但它返回null。如果我将这两个属性与“OR”||结合起来运算符我会得到结果,但如果项目符合两个条件,则会得到所有双重结果。
var articleList = (from item in doc.Descendants("item")
from _category in item.Elements("category")
where _category.Value == valueCboChannel && _category.Attribute("domain").Value == "Channel"
&& (_category.Value == valueCboSubChannel && _category.Attribute("domain").Value == "SubChannel")
select new
{
Title = item.Element("title").Value,
Guid= item.Element("guid").Value,
description = item.Element("description").Value,
link = item.Element("link").Value
}).ToList();
ListView1.DataSource = articleList;
ListView1.DataBind();
答案 0 :(得分:3)
我用扩展方法简化它来进行棘手的查找:
(2009年2月12日更新,以排除空元素)
static string CategoryValue(this XElement element, string type)
{
var category = element.Elements("category").FirstOrDefault(
c => (string)c.Attribute("type") == type
&& !string.IsNullOrEmpty(c.Value)); // UPDATE HERE
return category == null ? null : category.Value;
}
static void Main()
{
XDocument doc = XDocument.Parse(xml);
var qry = from item in doc.Descendants("item")
where item.CategoryValue("Channel") == "Automotive"
&& item.CategoryValue("Type") == "Cars"
select item;
foreach (var node in qry)
{
Console.WriteLine(node.Element("guid").Value);
}
}
答案 1 :(得分:0)
感谢您的提示,我设法以某种方式让它工作,但只在扩展方法中使用“.First”。
我现在面临的问题是如何获取xml文件中有NULL值的所有值。基本上,xml可能如下所示。因此,如果我使用“First”,那么当然第一个空的将被选中,因此不会显示。 有没有办法跳过NULL值?
<item>
<title>Industries</title>
<category type="Channel"></category>
<category type="Channel">Automotive</category>
<category type="Type"></category>
<category type="Type">Cars</category>
<category type="Token">Article</category>
<category type="SpecialToken">News</category>
<guid>637f0dd7-57a0-4001-8272-f0fba60feba1</guid>
</item>
这是当前的扩展方法
public static string CategoryValue(this XElement item, string type)
{
var category = item.Descendants("category").First(c => (string)c.Attribute("type") == type);
return category == null ? null : category.Value;
}