【问题标题】:How to create multiple entries in an xml file in VB.Net?如何在 VB.Net 的 xml 文件中创建多个条目?
【发布时间】:2019-04-20 22:05:03
【问题描述】:

单击按钮时,我需要将多个条目保存到 xml 文件中。目前,它只保存一个条目,然后它将覆盖xml文件以供下一个条目,每个xml文件只允许一个条目。

Private Sub btnXmlSave_Click(sender As Object, e As EventArgs) Handles btnXmlSave.Click

    Dim XmlSet As New XmlWriterSettings()
    XmlSet.Indent = True

    ' Initialize the XmlWriter.
    Dim XmlWrite As XmlWriter = XmlWriter.Create("MyCalc.xml", XmlSet)

    With XmlWrite

        ' create the XML file
        .WriteStartDocument()
        .WriteComment("XML Database.")
        .WriteStartElement("Data")

        .WriteStartElement("Calculations")

        ' write the tags and the entry into the tags
        .WriteStartElement("Number1")
        .WriteString(txtNum1.Text.ToString())
        .WriteEndElement()

        .WriteStartElement("Number2")
        .WriteString(txtNum2.Text.ToString())
        .WriteEndElement()

        .WriteStartElement("Operation")
        .WriteString(txtResult.Text.ToString())
        .WriteEndElement()

        'Close entry
        .WriteEndElement()
        .WriteEndDocument()
        .Close()

    End With

    ' provide feedback to the user that the file was saved
    MessageBox.Show("File 'MyCalc.xml' saved")

End Sub

预期的结果应该是这样的(我添加到应用程序创建的 XML 代码中):

<?xml version="1.0" encoding="utf-8"?>
<!--XML Database.-->
<Data>
  <Calculations>
    <Number1>34</Number1>
    <Number2>2</Number2>
    <Operation>34 - 2 = 32</Operation>
  </Calculations>
  <Calculations>
    <Number1>3</Number1>
    <Number2>2</Number2>
    <Operation>3 - 2 = 1</Operation>
  </Calculations>
</Data>

目前,代码会用第二个覆盖第一个(计算),所以我的程序不会显示这两个操作,它只会显示一个。我相信这可能是一个 For Each 循环,但我无法让它工作。

再次感谢您提供的任何帮助!

下面是获取xml数据的代码:

Private Sub btnXmlRetrieve_Click(sender As Object, e As EventArgs) Handles btnXmlRetrieve.Click

    Try

        If IO.File.Exists("MyCalc.xml") Then

            lstOutput.DataSource = Nothing
            lstOutput.Items.Clear()
            txtNum1.Clear()
            txtNum2.Clear()
            txtResult.Clear()

            Dim xmlDoc As New XmlDocument()
            Dim calcOrderNodes As XmlNodeList
            Dim calcOrderNode As XmlNode
            Dim num As Integer = 0

            xmlDoc.Load("MyCalc.xml")
            calcOrderNodes = xmlDoc.GetElementsByTagName("Calculations")

            For Each calcOrderNode In calcOrderNodes
                lstOutput.Items.Add(xmlDoc.GetElementsByTagName("Operation").Item(num).InnerText)
                num = num + 1
            Next

        Else

            MessageBox.Show("No operations were saved to a XML file.")

        End If

    Catch ex As Exception
        MessageBox.Show(ex.Message)

    End Try
End Sub

编辑

所以,我能够让它在应用程序中正确显示,但 xml 文件的组织不正确。我使用此代码附加(这就是它最初覆盖而不是添加的原因)。如果不存在文件,它会创建正确的 xml 结构,但一旦创建文件,它会保存但格式不正确。

新代码(为长篇道歉,试图修复它):

Private Sub btnXmlSave_Click(sender As Object, e As EventArgs) Handles btnXmlSave.Click

    Try
        If IO.File.Exists("MyCalc.xml") Then

            Dim xmlDoc As New XmlDocument()
            xmlDoc.Load("MyCalc.xml")

            Dim calc As XmlNode = xmlDoc.CreateElement("Calculations")
            Dim num1 As XmlNode = xmlDoc.CreateElement("Number1")
            Dim num2 As XmlNode = xmlDoc.CreateElement("Number2")
            Dim Op As XmlNode = xmlDoc.CreateElement("Operation")

            num1.InnerText = txtNum1.Text
            num2.InnerText = txtNum2.Text
            Op.InnerText = txtResult.Text

            xmlDoc.LastChild.AppendChild(calc)
            xmlDoc.LastChild.AppendChild(num1)
            xmlDoc.LastChild.AppendChild(num2)
            xmlDoc.LastChild.AppendChild(Op)

            xmlDoc.Save("MyCalc.xml")
        Else
            Dim XmlSet As New XmlWriterSettings()
            XmlSet.Indent = True

            ' Initialize the XmlWriter.
            Dim XmlWrite As XmlWriter = XmlWriter.Create("MyCalc.xml", XmlSet)

            With XmlWrite

                ' create the XML file
                .WriteStartDocument()
                .WriteComment("XML Database.")
                .WriteStartElement("Data")

                .WriteStartElement("Calculations")

                ' write the tags and the entry into the tags
                .WriteStartElement("Number1")
                .WriteString(txtNum1.Text.ToString())
                .WriteEndElement()

                .WriteStartElement("Number2")
                .WriteString(txtNum2.Text.ToString())
                .WriteEndElement()

                .WriteStartElement("Operation")
                .WriteString(txtResult.Text.ToString())
                .WriteEndElement()

                ' close entry
                .WriteEndElement()
                .WriteEndDocument()
                .Close()

            End With
        End If

    Catch ex As Exception
        MessageBox.Show(ex.Message)

    End Try

    ' provide feedback to the user that the file was saved
    MessageBox.Show("File 'MyCalc.xml' saved")

End Sub

xml 文件中的示例显示了它是如何保存的:

<?xml version="1.0" encoding="utf-8"?>
<!--XML Database.-->
<Data>
  <Calculations>
    <Number1>2</Number1>
    <Number2>1</Number2>
    <Operation>2 + 1 = 3</Operation>
  </Calculations>
  <Calculations />
  <Number1>3</Number1>
  <Number2>2</Number2>
  <Operation>3 / 2 = 1.50</Operation>
  <Calculations />
  <Number1>41</Number1>
  <Number2>2</Number2>
  <Operation>41 x 2 = 82</Operation>
</Data>

【问题讨论】:

  • 首先,您将需要多个条目,但从问题中的信息中不清楚它们来自哪里。
  • @AndrewMorton 这些条目来自应用程序中的文本框(txtNum1.Text、txtNum2.Text 和 txtResult.Text)。我希望用户能够输入一个计算,点击 xml 保存按钮,输入下一个计算并保存它。我计划设置一个计数器来限制每次程序运行时的条目数,但我还没有到达那里。
  • 你有读取 XML 文件的代码吗?如果是这样,那将更容易回答这个问题。
  • @AndrewMorton 我编辑了帖子以添加用于从 xml 文件中检索数据并将其放入列表框中的代码。我已经用多个条目对此进行了测试,它确实在列表框中放置了多个(操作),即当我在 xml 文件中添加条目时(手动)。我需要程序能够添加多个条目而不覆盖它们。

标签: xml vb.net


【解决方案1】:

试试这个:

If IO.File.Exists("MyCalc.xml") Then
        Dim xmlDoc As New XmlDocument()
        xmlDoc.Load("MyCalc.xml")

        Dim mainNode As XmlNode = xmlDoc.DocumentElement
        Dim newOp As XmlNode = xmlDoc.CreateElement("Calculations")

        'Create elements and append them to the main document node'
        Dim subNode As XmlNode = xmlDoc.CreateElement("Number1")
        subNode.InnerText = txtNum1.Text
        newOp.AppendChild(subNode)

        subNode = xmlDoc.CreateElement("Number2")
        subNode.InnerText = txtNum2.Text
        newOp.AppendChild(subNode)

        subNode = xmlDoc.CreateElement("Operation")
        subNode.InnerText = txtResult.Text
        newOp.AppendChild(subNode)

        'append child node to main node and save'
        mainNode.AppendChild(newOp)
        xmlDoc.Save("MyCalc.xml")
Else
        'Add other code here'
End If

【讨论】:

  • 做到了!非常感谢!我想我缺少的关键部分是 .DocumentElement 并将子节点附加到主节点。另外,代码更简洁,感谢您的帮助!
【解决方案2】:

是的,使用 for 循环或 for each 应该得到你想要的。

例如

Private Sub btnXmlSave_Click(sender As Object, e As EventArgs) Handles btnXmlSave.Click

Dim XmlSet As New XmlWriterSettings()
XmlSet.Indent = True

' Initialize the XmlWriter.
Dim XmlWrite As XmlWriter = XmlWriter.Create("MyCalc.xml", XmlSet)

With XmlWrite

    ' create the XML file
    .WriteStartDocument()
    .WriteComment("XML Database.")
    .WriteStartElement("Data")

     For index As Integer = 1 To 2

        .WriteStartElement("Calculations")

        ' write the tags and the entry into the tags
        .WriteStartElement("Number1")
        .WriteString(txtNum1.Text.ToString())
        .WriteEndElement()

        .WriteStartElement("Number2")
        .WriteString(txtNum2.Text.ToString())
        .WriteEndElement()

        .WriteStartElement("Operation")
        .WriteString(txtResult.Text.ToString())
        .WriteEndElement()

        'Close entry
        .WriteEndElement()

     Next

    .WriteEndDocument()
    .Close()

End With

' provide feedback to the user that the file was saved
MessageBox.Show("File 'MyCalc.xml' saved")

End Sub

更多信息可以在这里找到:https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/for-each-next-statement

使用https://www.jdoodle.com/compile-vb-dot-net-online 的工作示例 - 只需粘贴以下代码:

Imports System
Imports System.Xml

Public Class Test
Public Shared Sub Main()

Dim XmlSet As New XmlWriterSettings()
XmlSet.Indent = True



' Initialize the XmlWriter.
Dim XmlWrite As XmlWriter = XmlWriter.Create(Console.Out, XmlSet)

With XmlWrite

    ' create the XML file
    .WriteStartDocument()
    .WriteComment("XML Database.")
    .WriteStartElement("Data")

    For index As Integer = 1 To 2


    .WriteStartElement("Calculations")

    ' write the tags and the entry into the tags
    .WriteStartElement("Number1")
    .WriteString("1")
    .WriteEndElement()

    .WriteStartElement("Number2")
    .WriteString("2")
    .WriteEndElement()

    .WriteStartElement("Operation")
    .WriteString("result")
    .WriteEndElement()

   'Close entry
    .WriteEndElement()
     Next
    .WriteEndDocument()
    .Close()

   End With

  ' provide feedback to the user that the file was saved
   console.Write(XmlWrite.ToString())

   End Sub

   End Class

【讨论】:

  • 这适用于在 xml 文件中创建多个条目(正如我想做的那样),但我想我想要做的是附加一个 xml 文件以添加到它而不是覆盖它。所以......当用户输入新的计算并单击保存按钮时,它会将其添加到 xml 文件中。抱歉,如果我一开始没有澄清这一点。
  • 也许这有帮助:stackoverflow.com/questions/8797797/… 看起来他们可能一直在尝试做类似的事情。
  • 感谢您的链接,我一定会看看我是否可以修改它。我确实让应用程序正常工作(编辑了我的帖子),但 xml 文件格式不正确。更近了一步!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多