Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am trying to display data from this xml file:

C#
<?xml version="1.0" encoding="utf-8" ?>
<Prices>
  <PricePerItem>
    <Item Name="Milk, Low fat, 1Liter">11.2</Item>
    <Item Name="Butter">17</Item>
    <Item Name="Bread">12.2</Item>
    <Item Name="Cheese">15.5</Item>
  </PricePerItem>
  <PricePerKg>
    <Item Name="Apple, Jonagold">13.4</Item>
    <Item Name="Chicken">12.5</Item>
    <Item Name="Salad">9.6</Item>
    <Item Name="Fish, Salmon">14</Item>
  </PricePerKg>
</Prices>


I am trying to get out the values from each one.
I have a listbox and a button
Right now it displays like this
Milk,Low Fat, 1 Liter 11.21713.215.5
But i want it to display 11.2 for Milk because thats the value and not all the values from PricePerItem

this is my code for the button
C#
listBox1.Items.Clear();

            var xmlDoc = new XmlDocument();
            xmlDoc.Load(@"c:\users\morski\documents\visual studio 2013\Projects\Test\Test\prices.xml");

            XmlNodeList xnListPerItem = xmlDoc.SelectNodes("/Prices");


                foreach (XmlNode xn in xnListPerItem)
                {

                    string pricePerItem = xn["PricePerItem"].InnerText;

                    
                    //Adds pricePerItem
                    var pricePerItemList= new List<string>();

                    pricePerItemList.Add("Milk, Low fat, 1Liter" + pricePerItem);
                    pricePerItemList.Add("Butter" + pricePerItem);
                    pricePerItemList.Add("Bread" + pricePerItem);

                    foreach (var vItem in pricePerItemList)
                    {
                        
                        listBox1.Items.Add(vItem);
                        
                    }
Posted
Comments
Sergey Alexandrovich Kryukov 17-Jul-14 23:53pm    
"Display them..." — what "them"? What exactly do you want to show, how? Why? What's the problem?
—SA

1 solution

I suspect that a big part of the problem is xmlDoc.SelectNodes("/Prices") .
Why isn't it xmlDoc.SelectNodes("/Prices/PricePerItem/Item") ?

xn["PricePerItem"].InnerText is obviously wrong.

And you shouldn't be hard-coding items into pricePerItemList, whatever that is.

Have a look at this:

System.Xml.XmlNodeList xnListPerItem = doc.SelectNodes("/Prices/PricePerItem/Item");

var pricePerItemList= new System.Collections.Generic.List<string>();

foreach (System.Xml.XmlNode xn in xnListPerItem)
{
    string temp = System.String.Format ( "{0} {1}" , xn.Attributes [ "Name" ].Value , xn.InnerText ) ;
    pricePerItemList.Add(temp);
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900