![](/img/trans.png)
[英]Error: Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]' to type 'System.IConvertible'
[英]Linq query on Xdocument returns "System.linq.Enumerable+WhereSelectEnumerableIterator'2[system.XML.Linq.Xelement,System.String]
我正在使用以下XML:
<?xml version="1.0" encoding="windows-1252"?>
<hexML>
<head>
<title><![CDATA[ ]]></title>
<description><![CDATA Releases XML]]></description>
<flastmod date="2014-09-24T16:34:23 CET"/>
</head>
<body>
<press_releases>
<press_release id="1796256" joint_id="383320" language="fr" type="5">
<published date="2014-06-19T11:55:09 CET"/>
<categories>
<category id="75" label="French" keywords="language"/>
</categories>
<headline><![CDATA[Test Release for Website 3]]></headline>
<ingress></ingress>
<location href="http://rthrthrthrtrt.com/test.xml"/>
</press_release>
</press_releases>
</body>
</hexML>
我正在嘗試通過這段代碼獲取數據:
cp[cpt, 0] = (from c in xdoc.Descendants("press_release")
where (int)c.Attribute("id") == r
select c.Element("headline").Value).Single();
cp[cpt, 1] = (from c in xdoc.Descendants("press_release")
where (int)c.Attribute("id") == r
select (c.Element("published").Attribute("date").Value)).ToString();
cp[cpt, 3] = (from c in xdoc.Descendants("press_release")
where (int)c.Attribute("id") == r
select c.Element("location").Attribute("href").Value).ToString();
第一條指令正確返回:網站3的測試版本。另一方面,另外兩條返回“System.linq.Enumerable + WhereSelectEnumerableIterator'2 [system.XML.Linq.Xelement,System.String]”。
謝謝您幫忙
注意:我使用的是.NET V3.5
是的,那是因為您直接在查詢第二個和第三個值時調用ToString()
- 而在第一個操作中,您調用的是Single()
,它將返回單個字符串值。
基本上,不要在查詢上調用ToString()
。 如果你想要一個單獨的值,可以使用Single()
, First()
等。如果你想要多個值,迭代它們並依次對它們進行所需的操作 - 或者以適當的方式將它們連接在一起。
請注意,這與LINQ to XML無關 - 它正是LINQ to Objects所做的:
using System;
using System.Linq;
class Test
{
static void Main()
{
string[] values = { "a", "b", "c" };
var query = values.Where(x => true);
Console.WriteLine(query);
Console.WriteLine(string.Join(";", query));
}
}
輸出:
System.Linq.Enumerable+WhereArrayIterator`1[System.String]
a;b;c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.