C#如何从XML中读取数据并填充ListView

C#中从XML读取数据填充ListView需先设置View=View.Details并添加对应列,再用XDocument或XmlReader解析XML,提取字段创建ListViewItem添加到Items集合,注意空值处理、编码和大文件性能优化。

在C#中从XML读取数据并填充ListView,核心是解析XML(推荐使用XDocumentXmlReader),提取所需字段,再逐项添加到ListView的Items集合中。注意ListView需提前设置View = View.Details并定义Columns,否则无法正确显示多列数据。

准备ListView控件结构

确保ListView支持详细视图和列头,否则只显示图标或大图标模式,无法呈现表格化数据:

  • 在设计器或代码中设置:listView1.View = View.Details;
  • 手动添加列(与XML字段一一对应):listView1.Columns.Add("ID", 80); listView1.Columns.Add("Name", 120); listView1.Columns.Add("Age", 60);
  • 清空旧数据(可选):listView1.Items.Clear();

用XDocument解析XML并遍历节点

XDocument语法简洁,适合结构清晰、内存允许的中小型XML文件。假设XML如下:


  
    张三
    28
  

  
    李四
    32
  

对应C#代码:

  • 加载XML:XDocument doc = XDocument.Load("data.xml");XDocument.Parse(xmlString);
  • 查找所有Person节点:var persons = doc.Root?.Elements("Person");
  • 遍历并创建ListViewItem:foreach (var p in persons) { string id = p.Attribute("ID")?.Value ?? ""; string name = p.Element("Name")?.Value ?? ""; string age = p.Element("Age")?.Value ?? ""; ListViewItem item = new ListViewItem(id); item.SubItems.Add(name); item.SubItems.Add(age); listView1.Items.Add(item); }

处理常见问题

实际开发中容易遇到几个典型问题:

  • 空节点或缺失属性:务必用?.空条件操作符和?? ""提供默认值,避免NullReferenceException
  • 中文乱码:若XML文件含中文且显示为问号,确认文件保存为UTF-8(带BOM更稳妥),或用new XmlReaderSettings { Encoding = Encoding.UTF8 }配合XmlReader.Create()
  • 性能考虑:超大XML(如几十MB)建议改用XmlReader流式读取,避免一次性加载全部到内存
  • 数据类型转换:如需将Age转为int参与计算,用int.TryParse(age, out int result)而非直接int.Parse

补充:用XmlReader实现流式读取(适合大文件)

当XML体积较大时,XmlReader更节省内存:

  • 创建只进读取器:using var reader = XmlReader.Create("data.xml");
  • 循环读取节点:while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "Person") { string id = reader.GetAttribute("ID") ?? ""; reader.ReadToFollowing("Name"); string name = reader.ReadElementContentAsString(); reader.ReadToFollowing("Age"); string age = reader.ReadElementContentAsString(); /* 构造item并添加 */ } }
  • 注意:需手动控制读取位置,逻辑比XDocument稍复杂,但内存占用低