Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
                }
            }
        }
    }
}
like image 607
woodykiddy Avatar asked Sep 19 '13 09:09

woodykiddy


3 Answers

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

like image 132
Pranay Rana Avatar answered Nov 01 '22 00:11

Pranay Rana


I would use LINQ2XML..

XDocument doc=XDocument.Parse(xmlstr);
String response=doc.Elements("question")
                   .Where(x=>x.Attribute("id")==id)
                   .Single()
                   .Element("response")
                   .Value;
like image 32
Anirudha Avatar answered Oct 31 '22 22:10

Anirudha


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

//it works for me !!!!

like image 40
gustavo ortega Avatar answered Oct 31 '22 23:10

gustavo ortega