繁体   English   中英

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

[英]How to create multiple entries in an xml file in 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文件没有正确组织。 我使用此代码进行追加(这就是为什么它最初覆盖与添加相比)。 如果不存在文件,则会创建正确的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>

是的,使用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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM