2

I need to read XML doc looking like example below (short version)

<root>
 <data>
    <_0>
        <id>123</id>
        <status>complete</status>
        <datesubmitted>2014-07-07 10:35:45</datesubmitted>
        <question1>10</question1>
        <question2>Yes</question2>
        <question3></question3>
    </_0>
    <_1>
        <id>456</id>
        <status>complete</status>
        <datesubmitted>2014-07-07 11:05:45</datesubmitted>
        <question1>10</question1>
        <question2>Yes</question2>
        <question3></question3>
    </_1>
    <_2>
        <id>789</id>
        <status>complete</status>
        <datesubmitted>2014-07-07 12:15:45</datesubmitted>
        <question1>10</question1>
        <question2>Yes</question2>
        <question3></question3>
    </_2>
 </data>
</root>

By using suggestion posted here previously I was using LINQ to XML

XElement root = XElement.Load(@"c:\\Temp\\SurveyResponse.xml");

var data = from child in root.Elements("data").Elements()
                   select new
                   {
                       id = (int)child.Element("id"),
                       status = (string)child.Element("status"),
                       date = (string)child.Element("datesubmitted")

                   };

I have two questions How to extract questions without hard coding it in the LINQ query statement

 question1 = (string)child.Element("question1"),
 question2 = (string)child.Element("question2"),
 question3 = (string)child.Element("question3"),

I need to have ability to build some kind question collection where questions going to be extracted with correct index. Note: question all sorted out but not necessarily begins from 1. Thank you

1 Answer 1

1

You can get list of questions as dictionary with question number as key. Question number can be extracted from node name using substring starting after position of "n" in "question...", for example :

var data = from child in doc.Root.Elements("data").Elements()
           select new
           {
               id = (int)child.Element("id"),
               status = (string)child.Element("status"),
               date = (string)child.Element("datesubmitted"),
               questions = child.Elements()
                                .Where(o => o.Name.LocalName.StartsWith("question"))
                                .ToDictionary(t => int.Parse(t.Name.LocalName.Substring(8)), 
                                              t => (string)t)
           };

This way you can get any question by it's number/index, for example :

var data1 = data.FirstOrDefault();
var question2 = data1.questions[2];
Sign up to request clarification or add additional context in comments.

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.