如何在VB.Net的xml文件中创建多个条目?

时间:2019-04-20 22:05:03

标签: xml vb.net

单击按钮时,我需要将多个条目保存到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文件的组织不正确。我使用此代码来追加(这就是为什么它最初覆盖vs添加的原因)。如果没有文件,它将创建正确的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>

2 个答案:

答案 0 :(得分:0)

是的,使用for循环或每个循环都应该得到您想要的。

例如

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

答案 1 :(得分:0)

请尝试:

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