tags:

views:

48

answers:

1

I have an XML file:

<?xml version="1.0" encoding="us-ascii"?>
<TestItems xmlns="http://www.blogger.com"&gt;
  <TestItem correct="0" incorrect="0">
    <Question>question</Question>
    <Answer>answer</Answer>
    <Tags>test1;test2</Tags>
  </TestItem>
  <TestItem correct="0" incorrect="0">
    <Question>question3</Question>
    <Answer>answer3</Answer>
    <Tags>tagA;tagB;tagC</Tags>
  </TestItem>
</TestItems>

I also have an object:

class TestItem
{
    public string Question { get; set; }
    public string Answer { get; set; }
    public int NumberCorrect { get; set; }
    public int NumberIncorrect { get; set; }
    public string Tags { get; set; }
}

And here is the code that I use to read the data into memory:

XDocument ktdb = XDocument.Load("KTdb.xml");

XNamespace ns = ktdb.Root.Name.Namespace;

var testItems = from item in ktdb.Descendants(ns + "TestItem")
    select new TestItem
    {
        Question = item.Element(ns + "Question").Value,
        Answer = (string)item.Element(ns + "Answer").Value,
        Tags = item.Element(ns + "Tags").Value,
        NumberCorrect = Convert.ToInt32(item.Attribute(ns + "correct").Value),
        NumberIncorrect = Convert.ToInt32(item.Attribute(ns + "incorrect").Value)
    };

But it would not let me do that. When the LINQ statement is executed, the default constructor is called on the TestItem object, and then I get the null exception because item.Element(ns + "Question").Value is null.

Why do I get the error? How do I fix my code?

Thanks.

+3  A: 

Change this:

NumberCorrect = Convert.ToInt32(item.Attribute(ns + "correct").Value),
NumberIncorrect = Convert.ToInt32(item.Attribute(ns + "incorrect").Value)

To this:

NumberCorrect = Convert.ToInt32(item.Attribute("correct").Value),
NumberIncorrect = Convert.ToInt32(item.Attribute("incorrect").Value)

i.e. Remove the concatenation of ns from the attribute name.

Rob
Thanks, Rob. That was a stupid little thing I missed, but I swear that yesterday I tried loading just one element into a non-strongly-typed var set and it failed with the same error... Oh well, it was late at night so who knows what else I was doing wrong at the time. Thanks again.
Eugene