1

我正在尝试从以下位置提取<str>标签的内容:

<lst name="Stack">
  <lst name="Overflow">
     <arr name="content">
       <str>Help</str>
     </arr>
  </lst>
</lst>

我在 C# 中使用的代码是:

txtResponse.Text += xDoc.Descendants("lst")
        .Where(f => (string) f.Attribute("name") == "Overflow")
        .Descendants("arr")
        .Descendants("str")
        .Select(b => b.Value);

但它回到我身边

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]

我的问题是什么?

4

2 回答 2

2

该代码返回元素的集合(即枚举),而不是单个元素。在您的情况下,实际上是 a IEnumerable<string>,即“字符串列表”。该Text属性需要一个字符串。

从您的问题中不清楚 的内容txtResponse应该是什么样子,但您可以做这样的事情。

   var result = xDoc.Descendants("lst")
        .Where(f => (string) f.Attribute("name") == "Overflow")
        .Descendants("arr")
        .Descendants("str")
        .Select(b => b.Value);

   txtResponse.Text = string.Join(", ", result);
于 2013-08-27T11:31:52.927 回答
0

如果你只需要第一条记录,你只需要这个

txtResponse.Text += xDoc.Descendants("lst")
                   .Where(f => (string) f.Attribute("name") == "Overflow")
                   .Descendants("arr")
                   .Descendants("str")
                   .Select(b => b.Value)
                   .FirstorDefault();
于 2013-08-27T11:34:54.263 回答