I have an XML file:
<?xml version="1.0" encoding="us-ascii"?>
<TestItems xmlns="http://www.blogger.com">
<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.