如何使用vb.net创建XML文件?

时间:2019-04-04 20:03:35

标签: xml vb.net visual-studio-2017

我需要创建一个XML文件,该文件存储我的程序复制的所有文件的路由。

我正在尝试使用创建日志所需的相同代码。

Public Sub XMLRoutes(ByVal routeAs String)
    Dim xmlPath As String = "C:\Log\"

    'Create route if it doesn't exist
    If Directory.Exists(xmlPath) = False Then
        Directory.CreateDirectory(xmlPath)
    End If

    Dim xmlSW As System.IO.StreamWriter

    Dim Path As String = "C:\Log\CopiedRoutes.xml"

    If File.Exists(Path) = False Then
        Dim fs As FileStream = File.Create(Path)
    End If

    xmlSW.WriteLine("<route>" + route + "</route>")
    xmlSW.Flush()
    xmlSW.Close()

End Sub

但是我不知道它是否可以正常工作,也不知道如何放置起始标签

我希望我的结果像这样结束:

<?xml version='1.0' encoding='iso-8859-1'?>
<parameters>
  <route>route 1</route>
  <route>route 2</route>
  ...
</parameters>

1 个答案:

答案 0 :(得分:0)

恕我直言,使用XElement和XML文字使此过程变得容易。

''' <summary>
''' adds route to xml file
''' </summary>
''' <param name="route"></param>
''' <param name="pathToXML">the route xml file, will be created if does not exist</param>
Public Sub XMLRoutes(pathToXML As String, route As String)
    Dim xe As XElement
    If Not IO.File.Exists(pathToXML) Then
        'create the file
        xe = <ROUTES></ROUTES>
        xe.Save(pathToXML)
    Else
        xe = XElement.Load(pathToXML)
    End If
    Dim newRoute As XElement = <route><%= route %></route>

    xe.Add(newRoute)
    xe.Save(pathToXML)
End Sub

要使用

    Dim path As String = "C:\Log\CopiedRoutes.xml"
    XMLRoutes(path, "one")
    XMLRoutes(path, "two")