How to get value from a specific child element in XML using XmlReader?

woodykiddy picture woodykiddy · Sep 19, 2013 · Viewed 45.7k times · Source

Here's the XML string.

<?xml version="1.0" encoding="utf-16"?>
<questionresponses>
  <question id="dd7e3bce-57ee-497a-afe8-e3d8d25e2671">
    <text>Question 1?</text>
    <response>abcdefg</response>
    <correctresponse>123</correctresponse>
  </question>
  <question id="efc43b1d-048f-4ba9-9cc0-1cc09a7eeaf2">
    <text>Question 2?</text>
    <response>12345678</response>
    <correctresponse>123</correctresponse>
  </question>
</questionresponses>

So how could I get value of <response> element by given question Id? Say, if I give id value = "dd7e3bce-57ee-497a-afe8-e3d8d25e2671", I'd like to have string value abcdefg returned as result.

var xmlstr = "content from above xml example";
using (var reader = XmlReader.Create(new StringReader(xmlstr)))
{
    while(reader.Read())
    {
        if(reader.IsStartElement())
        {
            var attr = reader["id"];
            if(attr != null && attr == "dd7e3bce-57ee-497a-afe8-e3d8d25e2671")
            {
                if(reader.ReadToDescendant("response"))
                {
                    result = reader.Value; // <= getting empty string? So what's wrong?
                    break;
                }
            }
        }
    }
}

Answer

Pranay Rana picture Pranay Rana · Sep 19, 2013

you might need to do like this , problem i think is reader is not moving to text and because of that you are getting empty

        if(reader.ReadToDescendant("response"))
            {
                reader.Read();//this moves reader to next node which is text 
                result = reader.Value; //this might give value than 
                break;
            }

Above one is working for me you can try out at your end