Search code examples
c#xmlxpathcomboboxxpathnavigator

Comparing comboBox.Slectedvalue with XML file node value using Xpath in C#


This is part of my XML file, and I have on my c# form a combo box that contains the names of the devices form the xml file which I've put there by using xpath navigator, plus a numeric up down, and finally a button I called Buy. what i wanna do is when I hit the button Buy I want the QUANTITY node value of the DEVICE node whos NAME node value equals to the combo box SelectedValue to increase by the number of the numeric up down value. In other words how can I select the QUANTITY node of a DEVICE element that has its NAME equal to the name in the combo box and the increase it by the value of the numeric up down of course using C#.

<INVENTORY>
<DEVICE ID="1">
    <NAME>Air Steerable Bagless Upright</NAME>
    <BRAND>Hoover</BRAND>
    <MODEL>UH72400</MODEL>
    <QUANTITY>23</QUANTITY>
    <BUYING_PRICE>189.99</BUYING_PRICE>
    <SELLING_PRICE>229.99</SELLING_PRICE>
</DEVICE>
<DEVICE ID="2">
    <NAME>Quietforce Bagged Canister</NAME>
    <BRAND>Hoover</BRAND>
    <MODEL>SH30050</MODEL>
    <QUANTITY>18</QUANTITY>
    <BUYING_PRICE>299.99</BUYING_PRICE>
    <SELLING_PRICE>334.99</SELLING_PRICE>
</DEVICE>
<DEVICE ID="3">
    <NAME>Corded Cyclonic Stick Vacuum</NAME>
    <BRAND>Hoover</BRAND>
    <MODEL>SH20030</MODEL>
    <QUANTITY>21</QUANTITY>
    <BUYING_PRICE>79.99</BUYING_PRICE>
    <SELLING_PRICE>109.99</SELLING_PRICE>
</DEVICE>

Solution

  • private void button2_Click(object sender, EventArgs e)//Button Buy clicking method
            {
                XmlDocument inventory = new XmlDocument();
                inventory.Load("Inventory.xml");
                string vacuumName = (string)vacuumsBox.SelectedItem;//vacuumBox is a comboBox that contains the vacuums names
                XmlNode rootElement = inventory.FirstChild.NextSibling;//first child is the xml encoding type tag not the root
    
                int quantity, newQuantity = 0;
                foreach (XmlNode device in rootElement.ChildNodes)
                {
                    if (String.Equals(device["NAME"].InnerText, vacuumName))
                    {
                        int number = Convert.ToInt32(vacuumsNumber.Value);//vacuumNumber is the name of the numeric up down
                        quantity = Int32.Parse(device["QUANTITY"].InnerText);
                        newQuantity = quantity + number;
                        device["QUANTITY"].InnerText = newQuantity.ToString();//Updating the QUANTITY node value.
                        inventory.Save("Inventory.xml");
                        continue;
                    }
                }