简体   繁体   English

在C#中使用Xpath将comboBox.Slectedvalue与XML文件节点值进行比较

[英]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. 这是我的XML文件的一部分,我在c#上有一个组合框,其中包含设备的名称,这些设备是我使用xpath导航器放置在xml文件中的设备的名称,外加一个向上的数字,最后还有一个按钮我叫买。 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. 我想要做的是当我按下“购买”按钮时,我希望DEVICE节点的QUANTITY节点值(其NAME节点值等于组合框SelectedValue)增加数字上下数值的数量。 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#. 换句话说,我该如何选择DEVICE元素的QUANTITY节点,使其NAME等于组合框中的名称,然后使用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>

Well, I think an iterating approach is easier to understand in this case. 好吧,我认为在这种情况下,迭代方法更容易理解。 What we want to do is find an XmlElement, that has a specified Name-element with the desired content. 我们要做的是找到一个XmlElement,它具有指定的Name-element和所需的内容。

It helps to think of the XmlDocument as a tree. 可以将XmlDocument视为树。 This tree has different nodes. 该树具有不同的节点。 The topmost node is the Inventory. The 最顶层的节点是Inventory. The Inventory. The Inventory`-Node has (in this case) three device subnodes. Inventory. The Inventory`节点具有(在这种情况下)三种设备子节点。 Every device subnode has subnodes as well (Name, Brand, etc.). 每个设备子节点也都有子节点(名称,品牌等)。 With that in mind its easy to find the quantity. 考虑到这一点,很容易找到数量。 We iterate over the tree and check if the name element matches the search string. 我们遍历树并检查name元素是否与搜索字符串匹配。 If it does, we get the value of the quantity element. 如果是这样,我们将获得数量元素的值。 Here is a small Console application illustrating a possible solution. 这是一个小的控制台应用程序,说明了可能的解决方案。 Keep in mind that this solution can cause exceptions if the XML is not well-formed (for instance the NAME element is missing). 请记住,如果XML格式不正确(例如,缺少NAME元素),则此解决方案可能会导致异常。

    static void Main(string[] args)
    {
        XmlDocument xdoc = new XmlDocument();

        string searchName = "Quietforce Bagged Canister";

        xdoc.LoadXml(@"<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></INVENTORY>");

        //this is the INVENTORY element. You might need to customize that, in case the INVENTORY is not the root
        XmlNode rootElement = xdoc.FirstChild;

        //-1 means that no mathing item was found.
        int quantity = -1;

        //Here we iterate over every device element
        foreach(XmlNode device in rootElement.ChildNodes)
        {
            //TODO: Validate XML first. Missing Elements can cause exceptions

            //We can access the child elements of the decives with their element name
            if(String.Equals(device["NAME"].InnerText, searchName))
            {
                quantity = Int32.Parse(device["QUANTITY"].InnerText);
                break;
            }
        }

        Console.WriteLine(quantity.ToString());
        Console.ReadLine();
    }

If you prefer a LINQ to SQL approach something like this would work. 如果您更喜欢LINQ而不是SQL方法,则可以使用类似的方法。

public string GetXML()
{
    return @"<root><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></root>";

}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    ///this would be your up down control

    var xml = XDocument.Parse(GetXML());
    var device = xml.Descendants("DEVICE").Where(d => d.Descendants("NAME").First().Value == "Air Steerable Bagless Upright");
    var quantity = Convert.ToInt16(device.Descendants("QUANTITY").First().Value);
    quantity++;
    device.Descendants("QUANTITY").First().Value = quantity.ToString();
    xml.Save(@"c:\temp\temp.xml");
}
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;
                }
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM