2013-08-27 25 views
1

我试图提取<str>标签从内容:XML内容提取C#

<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] 

什么是我的问题?

+2

已经有您以前的问题的答案:http://stackoverflow.com/questions/18462349/parsing-xml- content-c-sharp – MarcinJuraszek

+0

上一个问题是类似的,但有细微的差别 –

回答

2

该代码返回元素的集合(即枚举),而不是单个元素。在你的情况下,实际上是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); 
+0

这很好用,谢谢 –

0

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

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

'+ ='不能用于输入'字符串'和'方法组'错误 –

+0

我刚刚测试过这个并且工作正常。 – Ehsan