VB.NET实现XML文件新增多条条目求助(避免覆盖原有内容)
解决WinForm中XML保存多条条目及搜索问题
一、实现新增条目不覆盖原有内容
原代码每次保存都会重新创建XML文档,导致覆盖旧数据。我们需要修改逻辑:先判断文件是否存在,存在则加载现有文档并新增条目,不存在则创建新文档结构。
完整保存代码
Imports System.IO Imports System.Xml.Linq Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button8.Click Dim filename As String = "C:\Users\User\Desktop\Test.xml" Dim rtbText As String = RichTextBox1.Text Dim description As String = TextBox1.Text ' 验证输入有效性 If String.IsNullOrWhiteSpace(description) Or String.IsNullOrWhiteSpace(rtbText) Then MessageBox.Show("描述和内容不能为空") Return End If SaveEntryToXml(filename, description, rtbText) MessageBox.Show("保存成功") End Sub Private Sub SaveEntryToXml(filePath As String, description As String, content As String) Dim doc As XDocument Try ' 判断XML文件是否存在 If File.Exists(filePath) Then ' 加载现有XML文档 doc = XDocument.Load(filePath) Else ' 创建全新的XML文档(包含声明和根节点) doc = New XDocument( New XDeclaration("1.0", "utf-8", "yes"), New XElement("Log") ) End If ' 获取根节点<Log>,防止意外缺失时重建 Dim logRoot As XElement = doc.Element("Log") If logRoot Is Nothing Then logRoot = New XElement("Log") doc.Add(logRoot) End If ' 构造新的条目节点 Dim newEntry As New XElement("Entry", New XElement("EntryDescription", description), New XElement("EntryValue", content), New XElement("EntryDate", DateTime.Today.ToString("ddMMyy")) ) ' 将新条目添加到根节点下 logRoot.Add(newEntry) ' 保存文档 doc.Save(filePath) Catch ex As Exception MessageBox.Show("保存失败:" & ex.Message) End Try End Sub
二、按描述名称搜索对应文本
使用LINQ to XML实现快速查询,支持忽略大小写匹配,可根据需求调整为精确匹配。
搜索功能代码
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click Dim filename As String = "C:\Users\User\Desktop\Test.xml" Dim searchKeyword As String = SearchTextBox.Text.Trim() If String.IsNullOrWhiteSpace(searchKeyword) Then MessageBox.Show("请输入搜索关键词") Return End If Try If Not File.Exists(filename) Then MessageBox.Show("XML文件不存在") Return End If ' 加载XML文档 Dim doc As XDocument = XDocument.Load(filename) ' LINQ查询匹配的条目(忽略大小写) Dim matchedEntries = From entry In doc.Descendants("Entry") Where entry.Element("EntryDescription").Value.Equals(searchKeyword, StringComparison.OrdinalIgnoreCase) Select entry.Element("EntryValue").Value If matchedEntries.Any() Then ' 把匹配结果显示到RichTextBox,多结果用换行分隔 RichTextBox1.Text = String.Join(vbCrLf, matchedEntries) Else MessageBox.Show("未找到匹配的条目") End If Catch ex As Exception MessageBox.Show("搜索失败:" & ex.Message) End Try End Sub
说明
- 若需要精确匹配,移除
StringComparison.OrdinalIgnoreCase参数即可 - 可根据需求扩展:比如显示匹配条目的创建日期,或者支持模糊搜索(用
Contains替换Equals)
内容的提问来源于stack exchange,提问作者user1377723
相关产品推荐
相关产品推荐

