我有一个包含两种类型信息的XML文件 - 由SLvl
值确定的位置和作业类型。我希望将这些SearchTxt
值绑定到2个下拉列表(一个用于位置,一个用于作业类型),以用作我页面上的过滤器。
问题是我无法通过我的where子句来过滤SLvl
值。使用where子句,不返回任何结果。如果我删除它,查询会返回所有文本值。
C#
using System.Xml.Linq;
using System.Linq;
.....
// Loading from file
XDocument loaded = XDocument.Load(@"http://[LINKREMOVED]/vacancies.aspx");
// Query the data
var q = (from c in loaded.Descendants("items")
where c.Element("SLvl").ToString() == "0"
select c.Element("SearchTxt").ToString()).Distinct();
// Populate drop down
foreach(string name in q)
{
ddlLocation.Items.Add(new ListItem(name, name));
}
XML:
<VacancyMatch>
<items>
<SearchID>60</SearchID>
<SearchTxt>Scotland</SearchTxt>
<ParentID>0</ParentID>
<SearchCatID>1</SearchCatID>
<SLvl>1</SLvl>
<SubCat>1</SubCat>
</items>
<items>
<SearchID>92</SearchID>
<SearchTxt>Accounting</SearchTxt>
<ParentID>60</ParentID>
<SearchCatID>2</SearchCatID>
<SLvl>2</SLvl>
<SubCat>2</SubCat>
</items>
... More items here
</VacancyMatch>
我猜问题是数据处于同一水平?这是我第一次使用LINQ to XML,因此任何帮助都非常适合。 注意: XML由第三方提供,因此格式化取决于它们。
答案 0 :(得分:10)
删除.ToString()
并改为使用.Value
属性:
var values = loaded.Descendants("items")
.Where(i => i.Element("SLvl").Value == "0")
.Select(i => i.Element("SearchTxt").Value)
.Distinct();
在XElement上调用ToString()
将以文本形式返回整个节点。例如,如果我们将上述查询中的i.Element("SearchTxt").Value
更改为i.Element("SearchTxt").ToString()
,则会生成以下字符串:
<SearchTxt>Accounting</SearchTxt>
在这种情况下,访问Value
属性将提取节点的内部文本 - “Accounting”。
答案 1 :(得分:3)
此:
where c.Element("SLvl").ToString() == "0"
应该是:
where c.Element("SLvl").Value == "0"
您无法使用“ToString()”方法获取元素的值,而是需要读取它的“Value”属性。
对于您尝试获取元素值的任何其他行也是如此。
希望它有所帮助。
答案 2 :(得分:1)
我注意到一个问题,你在XElements上使用ToString(),这不是你想要的,我认为:),获取XElement的文本内容使用Value属性。
http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.value.aspx