繁体   English   中英

从ListBox C#Win表单读取XML文件内容

[英]Read XML File Content from a ListBox C# win forms

我有一个ListBox ,它有一些文件。 我有2个Panels ,它们的形式相同,每个Panel都有很多Labels ,这些标签是ListBox中已加载文件的对应标签。

每当用户选择每个文件时,然后在面板中显示所选文件的相应数据。

例如,这是文件内容之一:

  <connection>
    <sourceId>sdfsdf</sourceId>
    <description>test.sdfds.interact.loop.com</description>
    <uri>https://test.sdf.interact.loop.com/WITSML/Store/Store.asmx</uri>
    <username>sdfdsf</username>
    <organizationFilter>*</organizationFilter>
    <fieldFilter>*</fieldFilter>
  </connection>

列表框1:

private void Form1_Load(object sender, EventArgs e)
        {
            PopulateListBox(listbox1, @"C:\TestLoadFiles", "*.rtld");

        }

private void PopulateListBox(ListBox lsb, string Folder, string FileType)
        {
            DirectoryInfo dinfo = new DirectoryInfo(Folder);
            FileInfo[] Files = dinfo.GetFiles(FileType);
            foreach (FileInfo file in Files)
            {
                lsb.Items.Add(file.Name);
            }
        }

如何读取和显示数据? 有人请向我解释如何读取/解析目录中的xml文件并显示数据?

如果我理解正确,这应该可以帮助您入门。

string path = "C:\\TestLoadFiles.xml";
string xmldoc = File.ReadAllText(path);

using (XmlReader reader = XmlRead.Create(xmldoc))
{
    reader.MoveToContent();
    label_sourceId.Text = reader.GetAttribute("sourceId");
    label_description.Text = reader.GetAttribute("description");
    // ... for each label if everything will always be the same
    // might be better to read in the file, verify it, then set your labels
}

编辑:
实际上,切换可能会更好:

while (reader.MoveToNextAttribute())
{
  switch (reader.Name)
  {
    case "description":
      if (!string.IsNullOrEmpty(reader.Value))
        label_description.Text = reader.Value;
      break;
    case "sourceId":
      if (!string.IsNullOrEmpty(reader.Value))
        label_sourceId.Text = reader.Value;
      break;
    // ...
  }
}  

编辑2:

因此,列表框包含文件名。

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    string path = (string)listBox1.SelectedItem;
    DisplayFile(path);
} 
private void DisplayFile(string path)
{
    string xmldoc = File.ReadAllText(path);

    using (XmlReader reader = XmlRead.Create(xmldoc))
    {   

        while (reader.MoveToNextAttribute())
        {
          switch (reader.Name)
          {
            case "description":
              if (!string.IsNullOrEmpty(reader.Value))
                label_description.Text = reader.Value; // your label name
              break;
            case "sourceId":
              if (!string.IsNullOrEmpty(reader.Value))
                label_sourceId.Text = reader.Value; // your label name
              break;
            // ... continue for each label
           }
        }
    }
} 

暂无
暂无

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

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