在Xdocument上进行Linq查询返回"System.linq.Enumerable+WhereSelectEnumerableIterator'2[system.XML.Linq.Xelement,System.String]"

5

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>

我将尝试通过这段代码块获取数据:
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();

第一条指令返回正确结果: Test Release for website 3。 另外两条指令返回的是"System.linq.Enumerable+WhereSelectEnumerableIterator'2[system.XML.Linq.Xelement,System.String]"。 谢谢您的帮助。 注:我使用的是.NET V3.5。
1个回答

13

是的,那是因为您直接在第二个和第三个值的查询中调用了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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接