Reputation: 347
i am trying to retrieve all the child elements but getting System.Collections.ListDictionaryInternal. Object reference not set to an instance of an object error.
my c# code retrieve all the question on according to the test_id and category_id passed:-
public static List<Questions> GetQuestion_Catgy(int test_id, int ctgy_id)
{
try
{
XDocument data = XDocument.Load(docurl);
return (from exm in data.Descendants("test_details")
where exm.Attribute("id").Value.Equals(test_id.ToString())
from ctgy in exm.Descendants("category")
where ctgy.Attribute("id").Value.Equals(ctgy_id.ToString())
orderby (int)ctgy.Attribute("id")
select new Questions
{
quesID = Convert.ToInt32(ctgy.Attribute("id").Value),
quesSTRING = ctgy.Attribute("ques").Value,
quesRATE = Convert.ToInt32(ctgy.Attribute("rating").Value),
quesOPT1 = (string)ctgy.Element("opt1").Value,
quesOPT2 = (string)ctgy.Element("opt2").Value,
quesOPT3 = (string)ctgy.Element("opt3").Value,
quesOPT4 = (string)ctgy.Element("opt4").Value,
quesANS = Convert.ToInt32(ctgy.Element("ans").Value),
quesIMG = (string)ctgy.Element("img").Value
}).ToList();
}
catch (Exception ex)
{
throw new ArgumentException(ex.Data + "\n" + ex.Message);
}
}
my xml
<test_details id="1" name="test exam" time="30" marks="100" difficulty="1">
<category id="1" name="HTML">
<question id="1" ques="what is HTML ?" rating="5">
<opt1>Markup Language</opt1>
<opt2>Scripting Language</opt2>
<opt3>Server-Side Lanugae</opt3>
<opt4>Client-Side Language</opt4>
<ans>1</ans>
<img>null</img>
</question>
<question id="2" ques="what is LMTH ?" rating="5">
<opt1>Markup Language</opt1>
<opt2>Scripting Language</opt2>
<opt3>Server-Side Lanugae</opt3>
<opt4>Client-Side Language</opt4>
<ans>2</ans>
<img>null</img>
</question>
</category>
<category id="2" name="C#" />
</test_details>
Upvotes: 0
Views: 395
Reputation: 330
It looks like you need to go down an extra level to the 'question' elements if you want to access the ques
attribute. ctgy
will not have ques
.
Upvotes: 1
Reputation: 8459
Your error is on this line:
from ctgy in exm.Descendants("category")
The exm
elements are at the same level of your categories. You need to replace exm
with data
.
Example:
from ctgy in data.Descendants("category")
Upvotes: 0
Reputation: 13399
ctgy.Attribute("ques").Value
ctgy.Attribute("rating").Value
There is no such attribute.
Also do a null check before doing things like
(string)ctgy.Element("opt2").Value,
Upvotes: 0