0

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;
                  }
0

2 Answers 2

1

How about:

var fieldName = "text";
var text =
    xmlStories
    .Descendants("field")
    .Where(e => e.Attribute("name").Value.Equals(fieldName));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.