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

47,943

Solution 1

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

Solution 2

I would use LINQ2XML..

XDocument doc=XDocument.Parse(xmlstr);
String response=doc.Elements("question")
                   .Where(x=>x.Attribute("id")==id)
                   .Single()
                   .Element("response")
                   .Value;

Solution 3

if (reader.NodeType == XmlNodeType.Element)
{
    if(reader.Name == "response")
    {
        reader.read();
        var res = reader.Value;
    }
} 

//it works for me !!!!

Share:
47,943
woodykiddy
Author by

woodykiddy

Updated on July 24, 2022

Comments

  • woodykiddy
    woodykiddy almost 2 years

    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;
                    }
                }
            }
        }
    }
    
  • woodykiddy
    woodykiddy over 10 years
    Yeah, indeed, I was missing out reader.Read() which is why reader.Value is empty. Thanks for point this out quickly.
  • Moeez
    Moeez about 5 years
    Can you please see one of my question regarding the xml response?
  • Corey
    Corey over 3 years
    Do we need break; here?