【问题标题】:XML Content Extraction C# [duplicate]XML 内容提取 C# [重复]
【发布时间】:2013-08-30 02:58:21
【问题描述】:

我正在尝试从以下位置提取<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]

我的问题是什么?

【问题讨论】:

标签: c# asp.net xml linq


【解决方案1】:

代码返回元素的集合(即枚举),而不是单个元素。在您的情况下,实际上是IEnumerable&lt;string&gt;,即“字符串列表”。 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);

【讨论】:

  • 效果很好,谢谢
【解决方案2】:

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

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

【讨论】:

  • '+='不能应用于类型'string'和'method group'错误
  • 我刚刚对此进行了测试并且工作正常。
猜你喜欢
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多