简体   繁体   English

C#WinForms-从XML导入数据到列表框

[英]C# WinForms - Import Data to Listbox from XML

XML Code XML代码

-<RegionBox>

<Regions>fdzg</Regions>

<Regions>asgfasd</Regions>

<Regions>sdfadga</Regions>

<Regions>adsfgsfha</Regions>

</RegionBox>

How I save XML 我如何保存XML

 XElement element = new XElement("RegionBox");
        foreach (var item in listBox1.Items)
        {
            element.Add(new XElement("Regions", item));


            //DataRow listRow = ds.Tables["RegionBox"].NewRow();
            //listRow["List"] = listBox1.Items;
            //Console.WriteLine(item);
        }
        XDocument document = new XDocument();
        document.Add(element);
        document.Save("XMLFile2.xml");

I want to be able to import the data back into the List box currently I've tried 我想现在能够将数据导入回到我尝试过的“列表”框中

            ds.ReadXml("XMLFile2.xml");
        {
        for (int i = 0; i < ds.Tables["RegionBox"].Columns.Count; i++)
            listBox1.Items.Add(ds.Tables["Regions"].Rows[0][i].ToString());
        setImage.BackgroundImage = System.Drawing.Image.FromFile(filePath.Text);
        }

and

            XDocument xmlDoc = XDocument.Load("XMLFile2.xml");
        var items = (from i in xmlDoc.Descendants("Regions")
                     select new { Item = i.Element("Regions").Value }).ToList();
                     listBox1.DataSource = items;

But I can't seem to get it to import the information... though I have been successful with getting either the first item or the last item but only one and not all of the items can be imported 但是我似乎无法获得它来导入信息……尽管我已经成功地获取了第一项或最后一项,但是只能导入其中一个,而并非所有项目都可以导入

Thanks 谢谢

UPDATE:: just after posting this I found I continued my search and then found one that worked 更新::发布此消息后,我发现我继续搜索,然后发现一个可行的

            XElement element = XElement.Load("XMLFile2.xml");
        foreach (XElement item in element.Elements("Regions"))
        listBox1.Items.Add(item.Value);
  1. select new { Item = i.Element("Regions").Value }) is wrong,because the parameter i is already the element of Regions ,so you just need to change the code like select new { Item = i.Value }) select new { Item = i.Element("Regions").Value })是错误的,因为参数i已经是元素Regions ,所以你只需要改变,如代码select new { Item = i.Value })
  2. I dont't know whether you have set the DisplayMember ,maybe you should to add this code listBox1.DisplayMember = "Item"; 我不知道您是否已设置DisplayMember ,也许您应该添加此代码listBox1.DisplayMember = "Item";

Don't know if this will make much sense, but with regards to reading xml data and then displaying it - 不知道这是否有意义,但是关于读取xml数据然后显示它-

XmlTextReader xReader = new XmlTextReader("../../Products.xml");
        xReader.WhitespaceHandling = WhitespaceHandling.None;
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(xReader);
        Console.WriteLine("Please enter product...");
        string product = Console.ReadLine();
        XmlNodeList xNodeList = xDoc.DocumentElement.SelectNodes("//Products/Product");

        foreach (XmlNode xNode in xNodeList)
        {
            if (xNode.NodeType == XmlNodeType.Element)
            {
               // Console.WriteLine(xNode.NodeType.ToString() + " : " + xNode.Name + " =" + xNode.FirstChild.InnerText);
                if (xNode.FirstChild.InnerText == product)
                {
                    string name = xNode.FirstChild.InnerText;
                    string price = xNode.FirstChild.NextSibling.InnerText;
                    Console.WriteLine("Name: " + name + "... Price: R" + price);
                }
                else
                {
                    Console.WriteLine("No Price");
                }
            }
        }
        Console.ReadLine();

With the XML file being Products.xml - XML文件为Products.xml时-

<Products>
<Product>
    <name>Bread</name>
    <price>10</price>
</Product>
<Product>
    <name>Milk</name>
    <price>20</price>
</Product>
<Product>
    <name>Coke</name>
    <price>18</price>
</Product>
<Product>
    <name>BarOne</name>
    <price>7</price>
</Product>

Some explaining: 一些解释:

The XmlTextReader can only be accessed once you add the using System.Xml; 一旦添加了使用System.Xml,就只能访问XmlTextReader。 namespace, once you initialize a XmlTextReader (xReader), you can load it with an .xml file, mine is Products.xml which is found 2 folders back from the debug folder, hence the ("../../") - skipping two folders back, which is actually the root folder but 2 folders out of the "debug" folder. 命名空间,一旦初始化XmlTextReader(xReader),就可以使用.xml文件加载该文件,而我的是Products.xml,该文件位于debug文件夹后面的两个文件夹中,因此(“ ../../”)-向后跳过两个文件夹,实际上是根文件夹,但在“ debug”文件夹中只有2个文件夹。

The xmlNodeList selects nodes, what I did there is only select up to Product, so the next node is name, and the next sibling node after that is price. xmlNodeList选择节点,我所做的只是选择Product,因此下一个节点是name,之后的下一个同级节点是price。

I'm sure the foreach loop is self explanatory, the first if statement makes sure the node is an element, the second if statement checks if the product name (bread, milk, etc) matches that what the user inputted in the beginning. 我确定foreach循环是可以自我解释的,第一个if语句确保节点是一个元素,第二个if语句检查产品名称(面包,牛奶等)是否与用户开头输入的内容匹配。 If it does, then a string is made, and named "name", because the first child is the name, and we want the name's node value, so innerText will get that for us. 如果是这样,那么将创建一个字符串,并将其命名为“ name”,因为第一个子代是名称,并且我们需要该名称的节点值,所以innerText将为我们获取该值。

To get the price, we just say xNode.FirstChild.NextSibling.InnerText, this will move from the to the next node, which is which is what we want. 为了获得价格,我们只说xNode.FirstChild.NextSibling.InnerText,它将从移到下一个节点,这就是我们想要的。

Hope this helps? 希望这可以帮助?

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

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