简体   繁体   English

将XML数据添加到列表框

[英]Add XML data to listbox

Total C# beginner here working on my first simple task list app from a windows form. 总的C#初学者在这里从Windows窗体开发我的第一个简单任务列表应用程序。

I am trying to import data from an XML file into a listbox, however I keep encountering the problem that instead of the actual data (eg "Pick up groceries", "Fix car", "Get better at this!") I keep getting lots of other data such as " 我试图将数据从XML文件导入到列表框中,但是我一直遇到这样的问题,而不是实际数据(例如“捡杂货”,“修复汽车”,“做得更好!”)许多其他数据,例如“

DocumentProperties xmlns="um.schemas-microsoft-come:office:office"

.... etc ....等

I start off by loading the dialog box to select the file (saving as string 'file'). 我首先通过加载对话框来选择文件(另存为字符串“ file”)。

My code is then; 然后是我的代码;

XDocument doc = XDocument.Load(file);

foreach (XElement el in doc.Root.Elements())
{
  el.ToString();
  var task = el;
  listBox1.Items.Add(task);
}

I have tried a few different approaches and no luck reading from my test xml file. 我尝试了几种不同的方法,但是从我的测试xml文件中读取结果没有运气。 Is there something simple I am missing? 有什么简单的我想念的吗?

Thanks in advance for your help. 在此先感谢您的帮助。

Your mistake is that you don't specify the TagName, for your root xml document. 您的错误是您没有为根xml文档指定TagName。 This is an example how to read a XML file : 这是一个如何读取XML文件的示例:

My XML File : 我的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<head>
  <Config>
      <port>80</port>
      <thread>5</thread>
      <gSave>0</gSave>
      <bSave>0</bSave>
  </Config>
</head>

And the example how to read that XML: 该示例如何读取该XML:

 protected string[] Config()
        {
            var retStrings = new[] {"","","",""};
            var xd = new XmlDocument();
            var fs = new FileStream("data/config.xml", FileMode.Open);
            xd.Load(fs);

            var list = xd.GetElementsByTagName("Config");
            for (var i = 0; i < list.Count; i++)
            {
                retStrings[0] = xd.GetElementsByTagName("port")[i].InnerText;
                retStrings[1] = xd.GetElementsByTagName("thread")[i].InnerText;
                retStrings[2] = xd.GetElementsByTagName("gSave")[i].InnerText;
                retStrings[3] = xd.GetElementsByTagName("bSave")[i].InnerText;
            }

            fs.Close();

            return retStrings;
        }

If you could show me your XML file, I would give you a specific example. 如果可以向我展示您的XML文件,请给我一个具体的例子。

Try the below snippet.. 尝试以下代码段。

DataSet ds = new DataSet();
ds.ReadXml(@"C:\demo.xml");

   if (ds.Tables.Count > 0)
{ 
     for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
     {
        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
          {
            listBox1.Items.Add(ds.Tables[0].Rows[i][j].ToString());
          }
     }
}

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

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