akniazi
akniazi

Reputation: 732

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="headlines"> 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;
                  }

Upvotes: 0

Views: 562

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 161002

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.

Upvotes: 0

Dave Fancher
Dave Fancher

Reputation: 386

How about:

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

Upvotes: 1

Related Questions