在 XML 文件中添加多个条目

问题描述 投票:0回答:1

我有一个包含 TextBox 和 RichTextBox 的表单。 RichTextBox 包含要由用户编辑的文本,TextBox 包含文本的描述性名称。我想将 RichTextBox 文本及其描述名称保存在 XML 文件中。 我正在使用以下代码来执行此操作。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button8.Click
    Dim filename As String = "C:\Users\User\Desktop\Test.xml"
    Dim doc As XDocument = Nothing
    Dim RTBText As String = RichTextBox1.Text
    Dim TextBoxText As String = TextBox1.Text
    createNode(TextBoxText, RTBText, doc)
    doc.Save(filename)
End Sub

Private Sub createNode(ByVal varname As String, ByVal varvalue As String, ByRef doc As XDocument)
    Dim identification As String = "<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?><Log></Log>"
    doc = XDocument.Parse(identification)
    Dim EntryData As XElement = doc.FirstNode
    Dim EntryDate = System.DateTime.Today.ToString("ddMMyy")
    Dim variables As New XElement("Entry", New Object() {
                                  New XElement("EntryDescription", varname),
                                  New XElement("EntryValue", varvalue),
                                  New XElement("EntryDate", EntryDate)
                                  })
    EntryData.Add(variables)

End Sub

代码生成以下 XML 文件。

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Log>
  <Entry>
    <EntryDescription>This is the TextTextbox Text</EntryDescription>
    <EntryValue>This is RTB Data</EntryValue>
    <EntryDate>181024</EntryDate>
  </Entry>
</Log>

该文件的条目不会超过几百个,这似乎没问题,但我不知道如何向文件添加其他条目。 事实上,下一个条目只会覆盖现有条目。 完成后,我需要能够搜索 XML 文件的描述性名称,然后检索随附的文本。 请有人协助找到一个解决方案,使我能够添加其他条目。

xml vb.net
1个回答
0
投票

我更喜欢使用 XElement 和 LINQ,

Public Class Form1

    Private doc As XElement = Nothing
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim filename As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        filename = IO.Path.Combine(filename, "FOOtest.xml")
        If doc Is Nothing Then
            If IO.File.Exists(filename) Then
                doc = XElement.Load(filename) 'open file if exists
            Else
                doc = <log></log> 'create new
                doc.Save(filename)
            End If
        End If
        createNode(TextBox1.Text, RichTextBox1.Text) 'add node
        doc.Save(filename) 'and save
    End Sub

    Private Sub createNode(varname As String,
                            varvalue As String)
        Dim EntryDate As String = System.DateTime.Now.ToString("ddMMyy")
        Dim variables As XElement
        'build a new entry
        variables = <Entry>
                        <EntryDescription><%= varname %></EntryDescription>
                        <EntryValue><%= varvalue %></EntryValue>
                        <EntryDate>181024</EntryDate>
                    </Entry>
        doc.Add(variables) 'add to existing
    End Sub
End Class
© www.soinside.com 2019 - 2024. All rights reserved.