0

我正在尝试检索所有子元素,但获取 System.Collections.ListDictionaryInternal。对象引用未设置为对象错误的实例。

我的 c# 代码根据传递的 test_id 和 category_id 检索所有问题:-

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);
            }
        }

我的 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>

在此处输入图像描述

4

3 回答 3

1

ques如果您想访问该属性 ,您似乎需要对“问题”元素再降低一层。ctgy不会有ques

于 2013-01-09T22:34:57.363 回答
0
ctgy.Attribute("ques").Value
ctgy.Attribute("rating").Value

没有这样的属性。

在做类似的事情之前做一个空检查

(string)ctgy.Element("opt2").Value,
于 2013-01-09T22:28:16.397 回答
0

您的错误在这一行:

from ctgy in exm.Descendants("category")

这些exm元素与您的类别处于同一级别。您需要替换exmdata.

例子:

from ctgy in data.Descendants("category")
于 2013-01-09T22:31:54.317 回答