0

我有一个ListBox&它有一些文件。我有 2 个Panels相同的格式,每个Panel都有很多LabelsListBox.

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

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

  <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 文件并显示数据????

4

1 回答 1

1

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

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
           }
        }
    }
} 
于 2012-05-09T15:08:48.427 回答