Retrieving XML elements - What am I doing wrong?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Greetings all,
Im trying to learn about retrieving, storing, and editing data in an XML file. Im still fairly new to C#, but I always seem to get caught on snags here and there. The help files and TechNet helped in getting started, but I find myself stuck
now.
I have a Form ("frmFavoriteFoods"). On this form I have a ComboBox ("cbFavoriteFoods"), and 4 TextBoxes ("txtFoodName", "txtFoodCountry", "txtFoodTaste", "txtFoodComments").

My XML file that I added to the project looks like this:
<pre class="prettyprint <FoodList>
<Food FoodName="Pizza
<FoodTaste>Spicey</FoodTaste>
<FoodCountry>Italy</FoodCountry>
<FoodComments>Has All 5 Food Groups In It! Super Healthy!</FoodComments>
</Food>
<Food FoodName="Sushi
<FoodTaste>Fishy</FoodTaste>
<FoodCountry>Japan</FoodCountry>
<FoodComments>Maguro And Shake Are Great</FoodComments>
</Food>
<Food FoodName="Bread
<FoodTaste>Yeasty</FoodTaste>
<FoodCountry>All</FoodCountry>
<FoodComments>Best. Food. Ever. Great With Everything!</FoodComments>
</Food>
<Food FoodName="Hamburgers
<FoodTaste>Beefy</FoodTaste>
<FoodCountry>America</FoodCountry>
<FoodComments>A Better Way To Eat Salad (On Top Of Meat, Between Buns).</FoodComments>
</Food>
</FoodList>[/code]
<br/>

When the Form loads, I wanted to load up the ComboBox with the names of the types of food.
<pre class="prettyprint private void frmFavoriteFoods_Load(object sender, EventArgs e)
{
XmlTextReader xmlReader = new XmlTextReader("..\..\FoodList.xml");

while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
while (xmlReader.MoveToNextAttribute())
if (xmlReader.Name == "foodName")
{
// Read the foodName attribute.
cbFavoriteFoods.Items.Add(xmlReader.Value);
}
}
}
}[/code]
After the form loads, I want to click the ComboBox and select an item from it. When I do this, I want the child elements for each XML node to get added to the TextBoxes, for whichever item I chose.
<pre class="prettyprint private void cbFavoriteFoods_SelectedIndexChanged(object sender, EventArgs e)
{
XmlTextReader xmlReader = new XmlTextReader("..\..\FoodList.xml");
while (xmlReader.Read())
{
if (xmlReader.Name == "FoodName")
{
if (xmlReader.Value == cbFavoriteFoods.SelectedItem.ToString())
{
// Does not get reached.
// I want to display the Food information at this point.
}
}
}
}[/code]
Does this make sense? If I add a ListBox to my form called lbTest, I can add lbTest.Items.Add(xmlReader.Value); just under the "While" segment, and it displays each element until the end of the document. But Im not sure how to "dig" deeper
than that.
Could someone please help me?

Thanks!

View the full article
 
Back
Top