I'm having a bit of an issue. I'm trying to parse an XML file and put it's contents into a TreeView. I got everything pretty much working, but I'm having issues with one thing.
Here is an example of the XML file:
<AnswerIt>
<category name="Category 1">
<question is="Question 1">
<answer couldbe="Answer 1" />
<answer couldbe="Answer 2" />
</question>
</category>
<category name="Category 2">
<question is="Question 1">
<answer couldbe="Answer 1" />
</question>
<question is="Question 2">
<answer couldbe="Answer 1" />
</question>
</category>
</AnswerIt>
The code I am using to prase the XML file pulls all the categories just fine. When it gets to the question part it pulls the first question, but none after that. All the answers get pulled just fine (as long as they belong to the first question). Here is my C# code:
public void LoadQuestionDatabase()
{
XmlTextReader reader = new XmlTextReader("http://localhost/AnswerIt.xml");
TreeNode node = new TreeNode();
TreeNode subnode = new TreeNode();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "category")
{
node = lstQuestions.Nodes.Add(reader.GetAttribute(0));
categories.Add(reader.GetAttribute(0));
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.Name == "question")
{
subnode = node.Nodes.Add(reader.GetAttribute(0));
questions.Add(reader.GetAttribute(0));
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.Name == "answer")
{
// add each answer
subnode.Nodes.Add(reader.GetAttribute(0).Replace("\t", ""));
}
}
}
}
}
}
reader.Close();
}
I'm not very good at C#, I'm guessing somewhere along the lines it's not looping through all the questions and adding them. Any ideas what I'm doing wrong? Anywhere I can read up on to help me out? Every example I read puts the root node (AnswerIt) in the treeview, and I do not want that.
var xDocument = XDocument.Load("http://localhost/AnswerIt.xml");
foreach (var element in xDocument.Descendants("category"))
{
var node = lstQuestions.Nodes.Add(element.Attribute("name").Value);
foreach (var subElement in element.Elements("question"))
{
var subnode = node.Nodes.Add(subElement.Attribute("is").Value);
foreach (var answer in subElement.Elements("answer"))
subnode.Nodes.Add(answer.Attribute("couldbe")
.Value.Replace("\t", ""));
}
}