开发者

Retrieving data from xml string

i am retrieving data from guardian web service using c#. The answer i get is the xml string which is something like this

< results >

< content >

< fields >

< field name="headline开发者_JS百科s"> This is headline < /field>
< field name="text"> This is text < /field>
<field name="url"> This is url < /field>
< fields>
< /content>
< content>
.........
< /content>
....
< results>

The problem is that all the nodes having data have same name that is "field". When i use this code it return the data from the first field node but I want the data from the field named text.

  var head = xmlStories.Root.Descendants("fields").Select(results => new
                  {
                      Text = results.Element("field").Value,


                  }).ToList();

                  foreach (var results in head)
                  {



                     text [h] = results.Text;


                      h = h + 1;
                  }


How about:

var fieldName = "text";
var text =
    xmlStories
    .Descendants("field")
    .Where(e => e.Attribute("name").Value.Equals(fieldName));


This would work:

var head = xmlStories.Descendants("field")
                     .Where(field =>(string)field.Attribute("name") == "text")
                     .Select(field => new
                      {
                        Text = (string)field,
                      })
                     .ToList();

Note the cast to string in the .Where() condition, this will cover the case where the attribute name is not present at all as well. If you just want a list with the content of that one string attribute you do not need an anonymous class either, shorter would be:

var head = xmlStories.Descendants("field")
                     .Where(field =>(string)field.Attribute("name") == "text")
                     .Select(field => (string)field)
                     .ToList();

This would be a list of strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜