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

时间:2012-05-09 14:29:46

标签: c# winforms visual-studio-2010 xml-serialization xml-parsing

我有ListBox&它有一些文件。我有两个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>

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

1 个答案:

答案 0 :(得分: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;
    // ...
  }
}  

EDIT2:

因此列表框包含文件名。

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
           }
        }
    }
}