I'm using the following 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>
I'm trying to get datas through this block of code:
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();
The first instruction returns correctly : Test Release for website 3. On the other hand , the 2 others returns "System.linq.Enumerable+WhereSelectEnumerableIterator'2[system.XML.Linq.Xelement,System.String]" instead.
Thank for your help
NB: I'm using .NET V3.5
Yes, that's because you've calling ToString()
directly on a query for your second and third values - whereas in the first operation, you're calling Single()
which will return a single string value.
Basically, don't call ToString()
on queries. If you want a single value, use Single()
, First()
etc. If you want multiple values, iterate over them and do what you want with each of them in turn - or join them together in some appropriate fashion.
Note that this has nothing to do with LINQ to XML - it's just what LINQ to Objects does:
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));
}
}
Output:
System.Linq.Enumerable+WhereArrayIterator`1[System.String]
a;b;c
See more on this question at Stackoverflow